How to Get a UNIX Timestamp in JavaScript or Node.js

The UNIX time is a way to describe a point in time. You’re describing the time using an integer value. This value is the number of seconds since the UNIX epoch which is the UTC time of 01 January 1970 at 00:00:00.

This tutorial shows you how to retrieve the UNIX timestamp in JavaScript.

Node.js Series Overview

Retrieve the UNIX Time in JavaScript

JavaScript’s global Date object comes with methods to interact with dates and times. The Date.now() function returns the current timestamp in milliseconds. These milliseconds are counted from the UNIX epoch. That means you need to convert these milliseconds to seconds and you’re receiving the UNIX time:

/**
 * Returns the current UNIX timestamp.
 *
 * @returns {Number}
 */
function unixTimestamp () {  
  return Math.floor(
    Date.now() / 1000
  )
}

That’s it! Enjoy using UNIX timestamps in JavaScript!

Explore the Library

Find interesting tutorials and solutions for your problems.