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
I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
PS: sadly someone merged this to the top answer without giving credit.
Quick and dirty solution:
Date.now() /1000 |0
Warning: it might break in 2038 and return negative numbers if you do the
|0
magic. UseMath.floor()
instead by that time
Math.floor()
solution:
Math.floor(Date.now() /1000);
Some nerdy alternative by Derek 朕會功夫 taken from the comments below this answer:
new Date/1e3|0
Polyfill to get Date.now()
working:
To get it working in IE you could do this (Polyfill from MDN):
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
If you do not care about the year / day of week / daylight saving time you could strip it away and use this after 2038:
var now = (function () {
var year = new Date(new Date().getFullYear().toString()).getTime();
return function () {
return Date.now() - year
}
})();
Some output of how it will look:
new Date() Thu Oct 29 2015 08:46:30 GMT+0100 (Mitteleuropäische Zeit ) new Date(now()) Thu Oct 29 1970 09:46:30 GMT+0100 (Mitteleuropäische Zeit )
Of course it will break daylight saving time but depending on what you are building this might be useful to you if you need to do binary operations on timestamps after int32 will break in 2038.
This will also return negative values but only if the user of that PC you are running your code on is changing their PC's clock at least to 31th of december of the previous year.
If you just want to know the relative time from the point of when the code was run through first you could use something like this:
var relativeTime = (function () {
var start = Date.now();
return function () {
return Date.now() - start
}
})();
In case you are using jQuery you could use $.now()
as described in jQuery's Docs which makes the polyfill obsolete since $.now()
internally does the same thing: (new Date).getTime()
If you are just happy about jQuery's version consider upvoting this answer since I did not find it myself.
Now a tiny explaination of what |0
does:
By providing |
, you tell the interpreter to do a binary OR operation. Bit operations require absolute numbers which turns the decimal result from Date.now() / 1000
into an integer.
During that conversion, decimals are removed, resulting in the same result as using Math.floor()
but using less code.
Be warned though: it will convert a 64 bit double to a 32 bit integer. This will result in information loss when dealing with huge numbers. Timestamps will break after 2038 due to 32 bit integer overflow.
For further information about Date.now
follow this link: Date.now() @ MDN