These JavaScript examples use Unix seconds for the portable baseline and show milliseconds only where the runtime exposes them naturally. The question to answer before copying a snippet is simple: what unit does the next API expect?
Get the current Unix time
const milliseconds = Date.now();
const seconds = Math.floor(milliseconds / 1000);
Convert a timestamp to UTC
const date = new Date(1700000000 * 1000);
console.log(date.toISOString());
Production note
Date accepts milliseconds, not Unix seconds. A 10-digit Unix value must be multiplied by 1000 before it becomes a Date.
Keep the unit in the field name when a value crosses a boundary: createdAtSeconds and createdAtMs are longer than createdAt, but much less mysterious during an incident.
Frequent questions:
- Q: Does Date.now() return Unix seconds?
- A: No. Date.now() returns milliseconds. Divide by 1000 and round down when an API, database, or command-line tool expects Unix seconds.
- Q: Should I store Date objects in JSON?
- A: No. Convert the value to a number or an ISO 8601 string first. JSON has no native Date type, so explicit values are easier to debug and compare.