How to get seconds since epoch in JavaScript?

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.