Advertisement
Advertisement


How do you get a timestamp in JavaScript?


Question

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 or a string.

2019/09/10
1
4087
9/10/2019 9:14:26 PM

Accepted Answer

Short & Snazzy:

+ new Date()

A unary operator like plus triggers the valueOf method in the Date object and it returns the timestamp (without any alteration).

Details:

On almost all current browsers you can use Date.now() to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).

You can easily make a shim for this, though:

if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}

To get 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 (also see this answer).

I would recommend using Date.now() (with compatibility shim). It's slightly better because it's shorter & doesn't create a new Date object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:

new Date().getTime()

Which you can then convert to seconds like this:

Math.round(new Date().getTime()/1000)

And you can also use the valueOf method which we showed 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());

2018/05/30
5009
5/30/2018 11:01:20 AM

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()
2017/11/30

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();
2011/05/30

var time = Date.now || function() {
  return +new Date;
};

time();
2014/12/16

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. Use Math.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

2018/04/04

var timestamp = Number(new Date()); // current time as number
2008/10/21

Source: https://stackoverflow.com/questions/221294
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]