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.

Node.js Series Overview

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 00:00:00 UTC.

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

const secondsSinceEpoch = Math.round( / 1000)

// is the same as

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

The and new Date().getTime() calls retrieve the milliseconds since the UTC epoch.

Convert the milliseconds since epoch 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.

How to Retrieve the UTC Seconds Since Epoch?

You may want to keep all dates in UTC format when working with them. Calculating the number of seconds since epoch using results in a date in your local timezone.

Here’s how to retrieve the number of seconds since epoch in UTC:

const now = new Date()  
const utcMilllisecondsSinceEpoch = now.getTime() + (now.getTimezoneOffset() * 60 * 1000)  
const utcSecondsSinceEpoch = Math.round(utcMilllisecondsSinceEpoch / 1000)  

The utcSecondsSinceEpoch variable contains the number of seconds elapsed since epoch and the current date, in UTC.

Calling date.getTimezoneOffset() returns the timezone difference of your current locale (host system settings) to UTC in minutes. You must then transform the minutes into milliseconds to calculate with the same units.

Explore the Library

Find interesting tutorials and solutions for your problems.