How do you get a timestamp in JavaScript?

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

    As of writing this, the top answer is 9 years old, and a lot has changed since then - not least, we have near universal support for a non-hacky solution:

    Date.now()
    

    If you want to be absolutely certain that this won't break in some ancient (pre ie9) browser, you can put it behind a check, like so:

    const currentTimestamp = (!Date.now ? +new Date() : Date.now());
    

    This will return the milliseconds since epoch time, of course, not seconds.

    MDN Documentation on Date.now

提交回复
热议问题