Dates and timestamps
overview
JS Dates are represented by millisecond timestamps: the number of milliseconds since Jan 1st 1970, 00:00 UTC (Unix Epoch).
read the timestamp
d_2021.getTime() // 1_609_459_200_000 (ms)
// getTimestamp() would be a better name
get the current timestamp with a helper:
Date.now() // 1_771_004_506_434 (ms)
new Date().getTime() // equivalent
build a Date from a timestamp:
new Date(1_627_541_982_738)
// '2021-07-29T06:59:42.738Z'
// Thu Jul 29 2021 08:59:42 GMT+0200 (Central European Summer Time)
For debugging, the Node.js REPL logs the date in its ISO 8601 format and in the UTC timezone, while the Chrome console logs a more verbose representation.
timestamp difference
d_1971.getTime() - d_1970.getTime() // 31 536 000 000 (ms)
compare date, check posteriority
We use the comparison operators on dates, to check posteriority. TypeScript allows comparison between objects.
d2021 > d2020
note on timestamp difference between Date objects (do not use)
In JS, We can subtract two Date objects, because they implement valueOf() which return their timestamp, and that is what the subtraction operates on:
d_1971 - d_1970 // 31 536 000 000 (ms)
The Typescript compiler doesn't allow it: it only sees a subtraction between objects and forbids it. It ignores the valueOf() transformation.