How to get the Unix timestamp in JavaScript

The Unix timestamp is an integer value that represents the number of seconds elapsed since the Unix Epoch on January 1st, 1970, at 00:00:00 UTC. In short, a Unix timestamp is the number of seconds between a specific date and the Unix Epoch.

The JavaScript Date object provides several methods to manipulate date and time. You can get the current timestamp by calling the now() function on the Date object like below:

const timestamp = Date.now()

This method returns the current UTC timestamp in milliseconds. The Date.now() function works in almost all modern browsers except IE8 and earlier versions. But you can fix this by writing a small polyfill:

if(!Date.now) {
    Date.now = () => new Date().getTime()
}

Otherwise, you can get the same timestamp by calling other JavaScript functions that work in older browsers too:

const timestamp = new Date().getTime()
// OR
const timestamp = new Date().valueOf()

To convert the timestamp to seconds (Unix time), you can do the following:

const unixTime = Math.floor(Date.now() / 1000)

The unixTime variable now contains the Unix timestamp for the current date and time, depending on the user's web browser.

It is recommended to use Date.now() whenever possible, even with polyfill. Unlike the getTime() method, it is shorter and doesn't create a new instance of the Date object.

If you are using a Unix-compatible machine like Ubuntu or macOS, you can also get the current Unix timestamp by typing the following command in your terminal:

$ date +%s
1567562058

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.