Categories
JavaScript Answers

How to get seconds since epoch in JavaScript?

Spread the love

Sometimes, we want to get seconds since epoch in JavaScript.

In this article, we’ll look at how to get seconds since epoch in JavaScript.

How to get seconds since epoch in JavaScript?

To get seconds since epoch in JavaScript, we get the timestamp of the datetime in milliseconds with getTime.

And then we divide that by 1000 to get the number of seconds since epoch.

For instance, we write

const d = new Date();
const seconds = d.getTime() / 1000;

to create the date d.

And then we call d.getTime to return the timestamp in milliseconds.

Then we divide that by 1000 to get the number of seconds since epoch.

Conclusion

To get seconds since epoch in JavaScript, we get the timestamp of the datetime in milliseconds with getTime.

And then we divide that by 1000 to get the number of seconds since epoch.

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 *