Each snippet starts from the same example: Unix seconds identify an instant, but each language's date API represents it differently. Pick a language below, verify the unit at the API boundary, then copy the result into production.
The short rule
- Most Unix and server-side APIs use seconds.
- JavaScript Date, Java, and .NET commonly expose milliseconds too.
- An ISO 8601 UTC string is often the clearest JSON representation.
- Use a named timezone for human display; keep UTC or an epoch value for storage and comparison.
These snippets deliberately avoid hidden local-time defaults. A timestamp that is correct on one developer laptop but changes on a CI server has not been converted safely.
Frequent questions:
- Q: Why does JavaScript use milliseconds for timestamps while other languages use seconds?
- A: JavaScript was designed for the browser where sub-second precision is useful for animations and event timing. The Date object was designed to use milliseconds since the Unix epoch. Most server-side languages (Python, PHP, Go, Ruby) default to seconds. Always check the documentation for the API you're working with.
- Q: How do I get the Unix timestamp in JavaScript without a library?
- A: Use Math.floor(Date.now() / 1000) for seconds or Date.now() for milliseconds. Both are built-in to every JavaScript runtime with no imports or dependencies.
- Q: How do I get the Unix timestamp in Python without a library?
- A: Use int(time.time()) from the built-in time module for seconds. For milliseconds: int(time.time() * 1000). For timezone-aware conversion use the datetime module with datetime.timezone.utc.