JS Dates and timestamps
overview
JS Dates store instants as millisecond timestamps. The timestamp is the number of milliseconds since Jan 1st, 1970 at 00:00:00 UTC, aka the Unix Epoch. Such timestamp identifies the instant unambiguously.
read the timestamp
d_2021.getTime()
// 1_609_459_200_000 (ms)
// hypothetical names: getEpochMs(), getTimestamp(), getInstant(),
build a Date from a timestamp:
new Date(1_627_541_982_738)
// 2021-07-29T06:59:42.738Z
use current time: omit timestamp
We create a current-time JS Date by omitting the timestamp:
new Date()
// 2026-04-25T09:29:08.530Z
(optional) We read the current-time timestamp with a helper:
Date.now()
// 1_777_109_775_765
compare dates, check distance and posteriority
timestamp difference:
d_1971.getTime() - d_1970.getTime() // 31 536 000 000 (ms)
We can use the comparison operators on dates to check for posteriority:
d2021 > d2020
d2021.getTime() > d2020.getTime() // pedantic
Note: In JS, We can subtract two Date objects, because they implement valueOf() which return their timestamp, and that is what the subtraction operates on. The Typescript compiler doesn't allow it.
/* do not use */
d_1971 - d_1970 // 31 536 000 000 (ms)
(advanced) date readability in consoles
new Date(1_627_541_982_738)
// 2021-07-29T06:59:42.738Z // Node.js
// Thu Jul 29 2021 08:59:42 GMT+0200 (Central European Summer Time) // Browsers
JavaScript consoles don't log dates as a millisecond timestamps. They log dates in a calendar format:
- the Node.js REPL logs the date in the ISO 8601 format (UTC).
- the browsers' console uses a lengthier calendar format, and shows the instant in the current timezone.