How do you get a timestamp in JavaScript?

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

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

    jQuery provides its own method to get the timestamp:

    var timestamp = $.now();
    

    (besides it just implements (new Date).getTime() expression)

    REF: http://api.jquery.com/jQuery.now/

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

    In addition to the other options, if you want a dateformat ISO, you get can get it directly

    console.log(new Date().toISOString());

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

    Date, a native object in JavaScript is the way we get all data about time.

    Just be careful in JavaScript the timestamp depends on the client computer set, so it's not 100% accurate timestamp. To get the best result, you need to get the timestamp from the server-side.

    Anyway, my preferred way is using vanilla. This is a common way of doing it in JavaScript:

    Date.now(); //return 1495255666921
    

    In MDN it's mentioned as below:

    The Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
    Because now() is a static method of Date, you always use it as Date.now().

    If you using a version below ES5, Date.now(); not works and you need to use:

    new Date().getTime();
    
    0 讨论(0)
  • 2020-11-21 15:31

    The code Math.floor(new Date().getTime() / 1000) can be shortened to new Date / 1E3 | 0.

    Consider to skip direct getTime() invocation and use | 0 as a replacement for Math.floor() function. It's also good to remember 1E3 is a shorter equivalent for 1000 (uppercase E is preferred than lowercase to indicate 1E3 as a constant).

    As a result you get the following:

    var ts = new Date / 1E3 | 0;
    
    console.log(ts);

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

    Any browsers not supported Date.now, you can use this for get current date time:

    currentTime = Date.now() || +new Date()
    
    0 讨论(0)
提交回复
热议问题