JavaScript Timestamp: The Complete Guide

How To Get Timestamp In Javascript | Javascript Timestamp Example

As a software developer, you can’t run away from date manipulation. Almost every app a developer builds will have some component where date/time needs to be obtained from the user, stored in a database, and displayed back to the user.

The UNIX timestamp is an integer representing the number of seconds that have elapsed since January 1, 1970.

How to Get Timestamp in Javascript

To get a current timestamp in JavaScript, use the function. The now() function get the current timestamp by calling on the Date object.

On UNIX-like machines, which include Linux and macOS, you can type the date +%s in the terminal and get the UNIX timestamp back.

How To Get Timestamp In Javascript

See the following code.

// app.js



timestamp using date now()

We can get the same value using the Javascript Date getTime() function.

// app.js

const date = new Date();



timestamp using gettime()

There is also one other method that can give the same result.

// app.js

const date = new Date();


Generally, timestamps are in milliseconds. However, we can convert it into seconds using the following code.

// app.js

const ts = Math.floor( / 1000);


Javascript Timestamp Example

Alternatively, you could use the following code, which is less readable.

// app.js

const dt = / 1000 | 0;

You can use a unary operator like plus(+) to trigger the valueOf method in the Date object, which returns the timestamp. See the following example.

// app.js

const date = + new Date();


unary operator to get timestamp in javascript

The problem with the unary operator code is that you instantiate a new Date object that’s immediately discarded.

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

You can use the following shim to get rid of IE8 issues.

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

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.