Seconds vs Milliseconds in Epoch Timestamps
Understand the difference between seconds-based and milliseconds-based epoch timestamps, how to detect which format you have, and avoid common conversion mistakes.
Detailed Explanation
Seconds vs Milliseconds Epoch Timestamps
One of the most common timestamp-related bugs is confusing seconds and milliseconds since the Unix epoch. Both formats are widely used, and mixing them up can lead to dates far in the past or future.
The Two Formats
| Format | Digits | Example | Date |
|---|---|---|---|
| Seconds | 10 | 1705312200 |
2024-01-15 09:30:00 UTC |
| Milliseconds | 13 | 1705312200000 |
2024-01-15 09:30:00 UTC |
Which Systems Use Which?
Seconds-based (10 digits):
- Unix/Linux
time()system call - Python
time.time() - PHP
time() - MySQL
UNIX_TIMESTAMP() - Most REST APIs
Milliseconds-based (13 digits):
- JavaScript
Date.now() - Java
System.currentTimeMillis() - Elasticsearch timestamps
- MongoDB ObjectId timestamps
- AWS DynamoDB TTL (seconds, but many SDKs return ms)
How to Detect the Format
A simple heuristic: count the digits.
10 digits → seconds (represents a date between 2001 and 2286)
13 digits → milliseconds (represents a date between 2001 and 2286)
If you accidentally interpret a seconds timestamp as milliseconds, you get a date in January 1970 (a few days after the epoch). If you interpret milliseconds as seconds, you get a date thousands of years in the future.
Safe Conversion
function toMilliseconds(timestamp) {
// If 10 digits, multiply by 1000
return timestamp < 10000000000 ? timestamp * 1000 : timestamp;
}
Common Pitfalls
- Off-by-1000 errors: Passing seconds to a function that expects milliseconds (or vice versa)
- Mixing in a single system: One microservice sends seconds, another expects milliseconds
- Database migration: Changing from one format to the other without updating all consumers
Use Case
Reference this guide when working with APIs, databases, or log files that use epoch timestamps. It helps prevent the extremely common bug of mixing up seconds and milliseconds, which can cause dates to appear as January 1970 or far in the future.