AppDividend
Latest Code Tutorials

How To Get Timestamp In Javascript | Javascript Timestamp Example

0

In this tutorial, we will see How To Get Timestamp In Javascript. 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 that represents the number of seconds elapsed since January 1, 1970.

How To Get Timestamp In Javascript

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

You can fetch the current timestamp by calling now() method on Date object.

// app.js

console.log(Date.now());

 

timestamp using date now()

We can get the same value by using the following function.

// app.js

const date = new Date();

console.log(date.getTime());

The output is following.

 

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. We can convert into the seconds using the following code.

// app.js

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

The output is following.

 

Javascript Timestamp Example

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

// app.js

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

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

// app.js

const date = + new Date();
console.log(date);

The output is following.

 

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(); }
}

Finally, How To Get Timestamp In Javascript | Javascript Timestamp Example is over.

Leave A Reply

Your email address will not be published.

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