The UNIX timestamp is the number of seconds since the UNIX epoch (January 01, 1970, 00:00:00 UTC). In this article, I am going to show you some ways to get that value in JavaScript.

To get a UNIX timestamp in JavaScript is quite simple, but there are 2 notes you need to keep in mind:

  • The JavaScript timestamp is in milliseconds, not in seconds
  • The leap seconds are ignored

Okay. Let’s do it step by step.

Step #1: Get the current JavaScript timestamp

const jsTimestamp = Date.now();
const jsTimestamp = new Date().getTime();
const jsTimestamp = new Date().valueOf();

Note:

  • new Date() returns a Date object that represents the date and time of instantiation.
  • Date.prototype.getTime() and Date.prototype.valueOf() are supported in IE8 and below, but Date.now() is not.
  • Use Date.prototype.getTime() instead of Date.prototype.valueOf() if possible due to the clarity of the code.

Need more ways to get the current timestamp?

const jsTimestamp = +new Date();
// or even ...
const jsTimestamp = +new Date;

Let me explain.

The unary plus operator calls the Date.prototype.valueOf() method, so you still get the result. The latter still works because JavaScript allows the parentheses to be omitted when constructing a new object with no arguments. It is weird, right? Hence, I do not recommend using these.

Step #2: Convert milliseconds to seconds

As the leap seconds are ignored, this step is straightforward. Just divide the number of milliseconds by 1000, then round the result down to the nearest integer.

const unixTimestamp = Math.floor(jsTimestamp / 1000);

The final code

const unixTimestamp = Math.floor(Date.now() / 1000);
const unixTimestamp = Math.floor(new Date().getTime() / 1000);
const unixTimestamp = Math.floor(new Date().valueOf() / 1000);