Categories
JavaScript Answers

How to Get the Number of Seconds Since Epoch in JavaScript?

Spread the love

Sometimes, we want to get the number of seconds since the Unix epoch, which is January 1, 1970 midnight UTC.

In this article, we’ll look at how to get the number of seconds since the Unix epoch with JavaScript.

Use the Date.prototype.getTime Method

The JavaScript date’s getTime method returns the Unix timestamp in milliseconds.

Therefore, we can use that to get the number of seconds since the Unix epoch by dividing the returned number by 1000.

We also need to round the result to the nearest integer.

For instance, we can write:

const d = new Date(2021, 1, 1);  
const seconds = Math.round(d.getTime() / 1000);  
console.log(seconds)

We create the d date that we want to get the number of seconds since the Unix epoch from.

To get the number of seconds since the Unix epoch, we call getTime on d .

Then we divide that by 1000.

And then we call Math.round to round the number.

Then we get that seconds is 1612166400.

Conclusion

We can get the number of seconds since the Unix epoch by using the getTime method to return the timestamp in milliseconds.

Then we convert the returned timestamp in seconds by dividing it by 1000.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *