How do you get a timestamp in JavaScript?

The explanation for the timestamp in JavaScript

Here we will know that how we can get a timestamp in JavaScript

This is now available on almost all current browsers where you can use Date.now() to get the UTC timestamp in milliseconds. 

You can easily make a shim for this, though:

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

If you want a timestamp in seconds, at that time you can use:

Math.floor(Date.now() / 1000)

Or you can use this in another way that is shown below:

Date.now() / 1000 | 0

This should be slightly faster. But it should be also readable.
Or else you can use Date.now() . This is slightly better because it is shorter & does not create a new Date object. And if you do not want to shim & maximum compatibility. So at such time you can use the “old” method to get the timestamp in milliseconds.

new Date().getTime()

After that one can convert them to seconds like as shown below

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

Also, there is another method called as valueOf . So you can use that. This method is as follows: 

new Date().valueOf()

Here we have Timestamp that is in a 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());

 

Also read, How to make Git “forget” about a file that was tracked

Share this post

5 thoughts on “How do you get a timestamp in JavaScript?

Leave a Reply

Your email address will not be published. Required fields are marked *