How do you get a timestamp in JavaScript?

前端 未结 30 3122
情深已故
情深已故 2020-11-21 15:19

How can I get a timestamp in JavaScript?

Something similar to Unix timestamp, that is, a single number that represents the current time and date. Either as a number

相关标签:
30条回答
  • 2020-11-21 15:35
    var timestamp = Number(new Date()); // current time as number
    
    0 讨论(0)
  • 2020-11-21 15:35

    For lodash and underscore users, use _.now.

    var timestamp = _.now(); // in milliseconds
    
    0 讨论(0)
  • 2020-11-21 15:37

    For a timestamp with microsecond resolution, there's performance.now:

    function time() { 
      return performance.now() + performance.timing.navigationStart;
    }
    

    This could for example yield 1436140826653.139, while Date.now only gives 1436140826653.

    0 讨论(0)
  • 2020-11-21 15:37

    Moment.js can abstract away a lot of the pain in dealing with Javascript Dates.

    See: http://momentjs.com/docs/#/displaying/unix-timestamp/

    moment().unix();
    
    0 讨论(0)
  • 2020-11-21 15:39

    If it is for logging purposes, you can use ISOString

    new Date().toISOString()

    "2019-05-18T20:02:36.694Z"

    0 讨论(0)
  • 2020-11-21 15:41

    The Date.getTime() method can be used with a little tweak:

    The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.

    Divide the result by 1000 to get the Unix timestamp, floor if necessary:

    (new Date).getTime() / 1000
    

    The Date.valueOf() method is functionally equivalent to Date.getTime(), which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.

    0 讨论(0)
提交回复
热议问题