
How to Get a Current Timestamp in JavaScript: Date.now vs getTime
When developing web applications, working with time data is a frequent requirement. You need timestamps to record log files, calculate elapsed times, display countdown timers, or synchronize events with a backend database.
In JavaScript, Unix timestamps are handled using the standard Date object.
However, developers face a common pitfall: JavaScript timestamps are measured in milliseconds, while most backends (like Python, Go, and MySQL) expect timestamps in seconds.
In this guide, we will compare the methods to retrieve millisecond timestamps in JavaScript, convert them to Unix seconds, and explore microsecond precision for measuring code performance.
1. Getting Milliseconds Timestamps
A millisecond timestamp represents the number of milliseconds that have elapsed since the Unix Epoch (January 1, 1970, 00:00:00 UTC).
Here are the three methods to retrieve this value:
Method A: Date.now() (Recommended)
This is the modern, cleanest, and fastest way. It returns the numeric timestamp directly without creating a new Date object memory allocation:
const milliseconds = Date.now();
console.log(milliseconds); // Outputs e.g., 1773756400000Method B: new Date().getTime()
This is the legacy method. It creates an instance of the Date object first, then invokes the getTime() method:
const milliseconds = new Date().getTime();
console.log(milliseconds); // Outputs e.g., 1773756400000- Note: This method is slightly slower than
Date.now()because it instantiates a full helper object in memory. Only use this if you already have a pre-existing date variable.
Method C: The Unary Plus Operator (+new Date())
This is a shorthand trick that leverages JavaScript's implicit type coercion. The unary plus operator forces the object to convert to a number, yielding the timestamp:
const milliseconds = +new Date();
console.log(milliseconds); // Outputs e.g., 1773756400000While compact, this syntax is less readable for junior developers and is generally avoided in team style guides.
2. Converting to Seconds (Unix Timestamp Standard)
Most databases (like PostgreSQL) and backend languages measure Unix timestamps in seconds (a 10-digit number) rather than milliseconds (a 13-digit number).
If you send a millisecond timestamp to a MySQL query expecting seconds, the database will interpret the date as being thousands of years in the future.
To convert milliseconds to seconds, divide by 1000 and discard the remainder using Math.floor():
// Convert current milliseconds to Unix seconds
const seconds = Math.floor(Date.now() / 1000);
console.log(seconds); // Outputs e.g., 1773756400- Note: Always use
Math.floor()orMath.round()to ensure you send an integer rather than a decimal value.
3. High-Precision Timestamps (performance.now)
If you are benchmarking code performance, calculating frame rates for game rendering loops, or measuring network delays, millisecond precision is insufficient.
In these scenarios, use performance.now() from the User Timing API:
const start = performance.now();
// Execute code test block
for (let i = 0; i < 1000000; i++) {}
const end = performance.now();
console.log(`Execution time: ${end - start} ms`); // Outputs e.g., "Execution time: 1.234567 ms"Key Differences of performance.now()
- Microsecond Precision: It returns a floating-point number with microsecond (one-millionth of a second) precision.
- Monotonic Time: Unlike
Date.now(), which reads your computer's system clock (meaning it can change if you adjust your timezone or if daylight savings starts),performance.now()measures time elapsed since the page loaded. It is guaranteed to move forward steadily.
Conclusion
Retrieving timestamps in JavaScript can be managed at varying precision levels. Use Date.now() to get the current time in milliseconds quickly for general logs, divide by 1000 combined with Math.floor() to match backend Unix second formats, and implement performance.now() when measuring execution speeds with microsecond accuracy.