JavaScript Timestamp: The Complete Guide

0
136
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 Date.now() 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

console.log(Date.now());

Output

timestamp using date now()

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

// app.js

const date = new Date();

console.log(date.getTime());

Output

timestamp using gettime()

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

// app.js

const date = new Date();

console.log(date.valueOf());

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

// app.js

const ts = Math.floor(Date.now() / 1000);
console.log(ts);

Output

Javascript Timestamp Example

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

// app.js

const dt = Date.now() / 1000 | 0;
console.log(dt);

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();
console.log(date);

Output

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 Date.now() 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 (!Date.now) {
    Date.now = 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.