Short and thick:
+ new Date()
An operator +
fires the method valueOf
in the object Date
and returns the timestamp (without any change).
Details:
In almost all current browsers, you can use Date.now()
to obtain the UTC timestamp in millisecond; a notable exception is the IE8 and previous (see compatibility table).
To obtain the timestamp in seconds, you can use:
Math.floor(Date.now() / 1000)
Or alternatively, you could use:
Date.now() / 1000 | 0
Which should be slightly faster but also less readable (see also this response).
I would recommend using Date.now ()
(with compatibility correction). It is a little better because it is shorter and does not create a new object Date
. However, if you do not want a maximum & compatibility fix, you can use the "old" method to get the timestamp in millisecond:
new Date().getTime()
Which you can then convert to seconds like this:
Math.round(new Date().getTime()/1000)
And you can also use the method valueOf
that we show above:
new Date().valueOf()
Timestamp in milliseconds
var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();
console.log(timeStampInMs, Date.now());
What would that be
Timestamp
? Remember that different systems have different ways of representing a date by a number. One of the most known is "Unix time" (32-bit or 64-bit), but there are others (Python for example uses afloat
instead of an integer). Verify that the format used by Javascript is the same as you need for your application. And if applicable, don’t forget to pay attention to the time zone.– mgibsonbr