Get Number of Seconds Since Epoch in JavaScript

Working with dates and times in JavaScript can be cumbersome. The Date class provides methods to interact with dates and times. Usually, you need to put more effort into calculating the value that you’re interested in.

In various situations, it’s favorable to calculate the seconds since epoch in JavaScript. The Unix epoch (also called Unix time) is the number of seconds since January 1st, 1970.

Here’s a code snippet showing you how to get the number of seconds since epoch:

const now = new Date()  
const secondsSinceEpoch = Math.round(now.getTime() / 1000)  

The .getTime() call gives you the milliseconds since epoch.

Convert them to seconds by dividing by 1000. This may create a decimal and you have to ensure an integer value by rounding to the next whole number. Otherwise, you may run into odd behavior when using the decimal value.

Explore the Library

Find interesting tutorials and solutions for your problems.