Why Your Date Shows 1970: Unix Timestamps in Seconds vs Milliseconds
Why Your Date Shows 1970: Unix Timestamps in Seconds vs Milliseconds You fetch a timestamp from an API, pass it to new Date(), and the screen says January 20, 1970. Or you get the opposite: a date in the year 55,840. Nothing is wrong with your date library. You've met the most common timestamp bug there is: mixing up seconds and milliseconds. What a Unix timestamp is Need to decode a timestamp…
Unix timestamps count the number of seconds or milliseconds since January 1, 1970. Different programming languages and systems use either seconds or milliseconds to represent these timestamps. When a program receives a timestamp from an API in one unit but expects it in another, it can lead to incorrect date outputs.
One common mistake is treating seconds as milliseconds, which results in a date showing January 20, 1970, instead of the correct date. To fix this, the number of seconds should be multiplied by 1000 to convert it to milliseconds before passing it to the `Date()` function.
Another mistake is treating milliseconds as seconds, which leads to a date showing the year 55,840. To address this, the number of milliseconds should be divided by 1000 to convert it to seconds before using it in the `Date()` function.
To avoid these issues, it's recommended to use the appropriate unit of measurement for timestamps in your code. For example, use `Date.now()` in JavaScript to get milliseconds, or `time.time()` in Python to get seconds. When receiving timestamps from an API, check the unit used by the API and convert it to the correct unit before using it in your code.
Naming the unit in database fields or API responses can help prevent this bug. For instance, use `createdAtMs` for milliseconds or `createdAtSec` for seconds. In API specifications, document the unit used for timestamps, and prefer using one unit consistently across the entire API.
When dealing with 32-bit signed integers for timestamps, be aware that they can overflow on January 19, 2038, at 03:14:07 UTC. To avoid this issue, use 64-bit integers for timestamps in new code.
A handy way to check if a timestamp is in seconds or milliseconds is to count the number of digits. If the timestamp has 10 digits, it's likely in seconds. If it has 13 digits, it's likely in milliseconds. However, this method may not work for timestamps before March 1973, so it's better to know the unit from the API documentation and convert it explicitly in production code.
By following these guidelines and being mindful of the unit used for timestamps, you can avoid common mistakes and ensure accurate date outputs in your applications.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.