Seconds vs Milliseconds
Avoid the most common timestamp bug
Seconds vs Milliseconds — Common Gotchas
One of the most frequent bugs when working with Unix timestamps is confusing seconds with milliseconds.
The Difference
| Unit | Typical Range | Used By |
|---|---|---|
| Seconds (10 digits) | 1710000000 |
POSIX, Linux, MySQL, PostgreSQL |
| Milliseconds (13 digits) | 1710000000000 |
JavaScript Date.now(), Java, C# |
JavaScript Example
JavaScript's Date.now() returns milliseconds:
const ms = Date.now(); // e.g., 1710000000000 (13 digits)
const seconds = Math.floor(ms / 1000); // e.g., 1710000000 (10 digits)
// Converting milliseconds to a Date:
const date = new Date(1710000000000); // ✅ Correct (ms)
// Common mistake: passing seconds to Date()
const wrong = new Date(1710000000); // ❌ Wrong — gives year 1970Python Example
Python's time.time() returns seconds (as a float):
import time
import datetime
# time.time() returns seconds (float)
now_seconds = time.time() # e.g., 1710000000.123
# Converting seconds to datetime
dt = datetime.datetime.utcfromtimestamp(now_seconds) # ✅ Correct
# Converting milliseconds to datetime
ms = 1710000000000
dt = datetime.datetime.utcfromtimestamp(ms / 1000) # ✅ Divide by 1000 firstSQL Example
-- PostgreSQL uses seconds
SELECT to_timestamp(1710000000); -- ✅ Correct
-- If you have milliseconds, divide first
SELECT to_timestamp(1710000000000 / 1000); -- ✅ CorrectHow to Quickly Detect the Unit
Check the number of digits:
- 10 digits (e.g.,
1710000000) → seconds - 13 digits (e.g.,
1710000000000) → milliseconds - 16 digits → microseconds
- 19 digits → nanoseconds
Best Practice
Always document the unit in your API contracts and database schemas:
// GOOD: explicit naming
interface Event {
createdAtSeconds: number; // Unix timestamp in seconds
updatedAtMs: number; // Unix timestamp in milliseconds
}
// BAD: ambiguous
interface Event {
timestamp: number; // What unit??
}