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.

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 retrieves the milliseconds since epoch in UTC.

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.

Can You Use

Sure, also returns the milliseconds since epoch:

const secondsSinceEpoch = Math.round( / 1000)  

The difference between new Date().getTime() and is that

  • returns the milliseconds since epoch for your timezone
  • new Date().getTime() always returns the UTC milliseconds

We like to go with .getTime() to ensure we’re always calculating with UTC timestamps.

Explore the Library

Find interesting tutorials and solutions for your problems.