4 Ways To Get The Current Timestamp In JavaScript


To get the current timestamp in JavaScript we can use 4 different methods as shown in below table.

Javascript MethodResult
Date.now();1561682894385
+new Date();1561682890500
new Date().getTime()1561682885990
new Date().valueOf()1561682881972

Timestamp (originated from UNIX) is an integer represents of the number of seconds elapsed since January 1 1970.

The above methods returns current timestamp in milliseconds.

There are Four methods to get the current timestamp in JavaScript, as listed below

Table of Contents

Get current timestamp javascript

Get current timestamp javascript

Get the current timestamp in JavaScript by using +new Date():

+new Date() returns the current timestamp in milliseconds.

The unary operator plus(+) in  +new Date() calls the valueOf() method in Date object and returns timestamp in milliseconds.

To get the timestamp in seconds use the following JavaScript code

Math.floor(+new Date() / 1000)

Get the current timestamp in JavaScript by using Date.now():

We can use Date.now() method in Date object to get the current timestamp in JavaScript in milliseconds.

Almost all browsers supports this method except IE8 and earlier versions.

It is better to use Date.now() to get the timestamp because of readability.

 Math.floor(Date.now() / 1000)
 // or you can use following javascript code to get timestamp in seconds
 Date.now() / 1000 | 0

The second method is little bit faster but lacks readability.

Get the current timestamp in JavaScript by using new Date().getTime():

For cross browser compatbility we can use getTime() method of Date object to get the current timestamp in milliseconds

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

Get the current timestamp in JavaScript by using new Date().valueOf():

Or we can use new Date().valueOf() method

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

 

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook or linkedn to get in touch with me.

Spread the word

Get free link to download 900+ Material Icons
Avatar
Arunkumar Gudelli

I am One among a million Software engineers of India. I write beautiful markup.I make the Web useful.

Next
Previous