How do you get a timestamp in JavaScript?

前端 未结 30 3118
情深已故
情深已故 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: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.

提交回复
热议问题