How can I get the current timestamp in JavaScript?

I’m looking for a simple way to get the current date and time as a single number in JavaScript, similar to a Unix timestamp (i.e., the number of seconds or milliseconds since January 1, 1970).

What’s the best method to generate a JavaScript timestamp like this?

Should I use Date.now() or is there a more accurate or preferred approach when working with time in milliseconds?

Hey @isha.tantia, The simplest and most common way to get a javascript timestamp (milliseconds since Jan 1, 1970) is using Date.now().

It returns the current time in milliseconds as a number, like this:

js
Copy
Edit
const timestamp = Date.now();
console.log(timestamp); // e.g., 1689324302345

It’s super fast, reliable, and widely supported in all modern browsers.

If you need seconds instead of milliseconds, just divide by 1000 and round it.

From my experience, you can also get the timestamp by creating a new Date object and calling .getTime(), like this:

js
Copy
Edit
const timestamp = new Date().getTime();
console.log(timestamp);

It does the same as Date.now(), but Date.now() is a bit cleaner and more straightforward for getting a javascript timestamp.

Both are accurate for most use cases.

If you want a quick and easy way to get a Unix-style timestamp in seconds (rather than milliseconds), here’s a handy trick:

js
Copy
Edit
const timestampSeconds = Math.floor(Date.now() / 1000);
console.log(timestampSeconds);

This way you get the javascript timestamp in seconds, perfect if you’re interfacing with APIs that expect timestamps in seconds rather than milliseconds.