Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a timestamp in JavaScript?

Something similar to Unix's timestamp, that is a single number that represents the current time and date. Either as a number or a string.

like image 666
pupeno Avatar asked Oct 21 '08 09:10

pupeno


People also ask

What is timestamp in JavaScript?

The UNIX timestamp is defined as the number of seconds since January 1, 1970 UTC. In JavaScript, in order to get the current timestamp, you can use Date. now() . It's important to note that Date. now() will return the number of milliseconds since January, 1 1970 UTC.

How do I make a timestamp?

Answer: Use the Date. now() Method You can simply use the JavaScript Date. now() method to generate the UTC timestamp in milliseconds (which is the number of milliseconds since midnight Jan 1, 1970).


2 Answers

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 or this with further explaination to bitwise operators).

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());
like image 127
daveb Avatar answered Oct 08 '22 05:10

daveb


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() 
like image 37
xer0x Avatar answered Oct 08 '22 04:10

xer0x