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
JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.
This will give you a Unix timestamp (in seconds):
var unix = Math.round(+new Date()/1000);
This will give you the milliseconds since the epoch (not Unix timestamp):
var milliseconds = new Date().getTime();
I highly recommend using moment.js
. To get the number of milliseconds since UNIX epoch, do
moment().valueOf()
To get the number of seconds since UNIX epoch, do
moment().unix()
You can also convert times like so:
moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()
I do that all the time. No pun intended.
To use moment.js
in the browser:
<script src="moment.js"></script>
<script>
moment().valueOf();
</script>
For more details, including other ways of installing and using MomentJS, see their docs
Today - 2020.04.23 I perform tests for chosen solutions. I tested on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0
Date.now()
(E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solutionperformance.now()
(G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on ChromeResults for chrome
You can perform test on your machine HERE
Code used in tests is presented in below snippet
function A() {
return new Date().getTime();
}
function B() {
return new Date().valueOf();
}
function C() {
return +new Date();
}
function D() {
return new Date()*1;
}
function E() {
return Date.now();
}
function F() {
return Number(new Date());
}
function G() {
// this solution returns time counted from loading the page.
// (and on Chrome it gives better precission)
return performance.now();
}
// TEST
log = (n,f) => console.log(`${n} : ${f()}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
This snippet only presents code used in external benchmark
Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
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
I like this, because it is small:
+new Date
I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better:
Date.now()