Timestamp guide
Unix timestamp in JavaScript
JavaScript Date.now returns milliseconds, while many APIs expect Unix seconds. The mismatch is a common source of wrong dates.
The JavaScript unit mismatch
In JavaScript, Date.now() returns the number of milliseconds since January 1, 1970 UTC. Many API fields, database examples, and command-line tools use Unix seconds instead. Passing one unit where the other is expected can move a date by a factor of one thousand.
Example
Date.now()
Math.floor(Date.now() / 1000)
Date.now() gives milliseconds. Math.floor(Date.now() / 1000) gives current Unix seconds.
How to convert in JavaScript
- Use Date.now() when the receiving system expects milliseconds.
- Use Math.floor(Date.now() / 1000) when the receiving system expects Unix seconds.
- When reading a timestamp, count the digits before converting it.
- Use ISO strings for bug reports when humans need to compare the exact moment.
Debug with both units visible
When a date looks wrong, convert the value as both seconds and milliseconds. If one lands near the expected date and the other lands in 1970 or far in the future, you have found the unit mismatch.
For current dates, Unix seconds are usually 10 digits and Unix milliseconds are usually 13 digits. That digit check is not a formal parser, but it catches the everyday JavaScript mistake quickly.
Common mistakes
- Sending Date.now() to an API field that expects seconds
- Multiplying a millisecond value by 1000 again
- Comparing local date strings without checking UTC
- Assuming every timestamp in logs uses the same unit
Related problems
FAQ
Does Date.now return seconds?
No. Date.now returns milliseconds since January 1, 1970 UTC.
How do I get Unix seconds in JavaScript?
Use Math.floor(Date.now() / 1000) for current Unix seconds.
Should I store seconds or milliseconds?
Match the API, database, or log format you already use, and name fields clearly so the unit is obvious.