How do you get a timestamp in JavaScript?

前端 未结 30 3545
情深已故
情深已故 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: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();
    

提交回复
热议问题