JS Date() and Timestamps
overview
The JS Date() is represented by a millisecond timestamp, milliseconds since Jan 1st 1970, 00:00:00 UTC (Unix Epoch).
read the timestamp
d_2021.getTime() // 1_609_459_200_000 (ms)
// getTimestamp() would be a better name
timestamp at read time:
Date.now() // 1_771_004_506_434 (ms)
build a Date from a timestamp:
new Date(1_627_541_982_738)
// '2021-07-29T06:59:42.738Z'
The REPL logs the date in its ISO 8601 format and in the UTC timezone for debugging.
timestamp difference
d_1971.getTime() - d_1970.getTime() // 31 536 000 000 (ms)
note on timestamp difference between Date objects (do not use)
In JS, We can subtract two Date objects: Date objects implement valueOf() to return the timestamp. The subtraction operator trigger this transformation and subtracts the timestamps. As such, the subtraction works on Dates
d_1971 - d_1970 // 31 536 000 000 (ms)
The Typescript compiler doesn't allow it: it sees a subtraction between objects, because it ignores valueOf().
compare date, check posteriority
We can use the comparison operators on dates, to check posteriority. TypeScript allows comparison between objects. We can also compare timestamps.
d2021 > d2020