Epoch in JavaScript

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in JavaScript.

// Use Date.now() to get the current timestamp in milliseconds
const now = new Date();
console.log(now);

// Get seconds since Unix epoch
console.log(Math.floor(now.getTime() / 1000));

// Get milliseconds since Unix epoch
console.log(now.getTime());

// Get nanoseconds since Unix epoch (JavaScript doesn't have nanosecond precision)
console.log(now.getTime() * 1000000);

// You can also convert integer milliseconds since the epoch into the corresponding Date
console.log(new Date(now.getTime()));
console.log(new Date(now.getTime()));

To run the program:

$ node epoch.js
2023-05-22T12:34:56.789Z
1684759696
1684759696789
1684759696789000000
2023-05-22T12:34:56.789Z
2023-05-22T12:34:56.789Z

In JavaScript, we use the Date object to work with dates and times. The Date.now() method returns the number of milliseconds since the Unix epoch.

Unlike some other languages, JavaScript doesn’t have built-in methods to get the time in seconds or nanoseconds since the epoch. However, we can easily calculate these:

  • For seconds, we divide the millisecond timestamp by 1000 and round down.
  • For nanoseconds, we multiply the millisecond timestamp by 1,000,000. Note that JavaScript doesn’t actually have nanosecond precision, so this is just an approximation.

To convert a timestamp back into a Date object, we can use the Date constructor with the millisecond timestamp.

Next, we’ll look at another time-related task: date parsing and formatting in JavaScript.