How to Get Unix Timestamp in JavaScript (Seconds vs Milliseconds)
Working with dates and timestamps in JavaScript can be slightly confusing because JS handles time in milliseconds, whereas standard Unix timestamps use seconds. Here is a quick reference guide to handle both correctly. Get Current Timestamp in Milliseconds By default, JavaScript's Date.now() returns the current timestamp in milliseconds:const timestampMs = Date.now(); console.log(timestampMs); //…
JavaScript's handling of time differs from the standard Unix timestamp format, which uses seconds rather than milliseconds. Here's a clear guide on managing both formats effectively.
To obtain the current time in JavaScript, the Date.now() method defaults to providing the timestamp in milliseconds. This can be seen by logging the following code snippet to the console:
const timestampMs = Date.now();
console.log(timestampMs);
The output will display the current time in milliseconds, such as 1726053000000.
When it comes to standard Unix timestamps, they are seconds-based. Thus, to convert the JavaScript timestamp into the traditional Unix seconds format, you simply need to divide the millisecond value by 1000 and then apply Math.floor() to round down to the nearest whole number:
const timestampSec = Math.floor(Date.now() / 1000);
console.log(timestampSec);
This will output the current time in Unix seconds, like 1726053000.
If you have a Unix timestamp expressed in seconds and need to convert it back into a JavaScript Date object, you must first multiply the timestamp by 1000. This will then be passed to the new Date() constructor to create the corresponding date object. Here's how you would do it:
const unixTimestamp = 1726053000;
const date = new Date(unixTimestamp * 1000);
console.log(date.toISOString());
This will generate an ISO 8601 formatted string representing the date and time, such as "2024-06-15T13:00:00.000Z."
For those who require a convenient tool to convert timestamps or explore timezones online, a quick-to-use web application has been developed for this purpose. It allows for instant conversions and timezone testing, providing a seamless experience at timestampeasy.com.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.