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
var timestamp = Number(new Date()); // current time as number
For lodash and underscore users, use _.now
.
var timestamp = _.now(); // in milliseconds
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
.
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();
If it is for logging purposes, you can use ISOString
new Date().toISOString()
"2019-05-18T20:02:36.694Z"
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.