Switch to infinite scroll (Full book)

JS Date API introduction

instants

JS Date objects represent and store instants (aka dates) as millisecond timestamps. The timestamp is the number of milliseconds since Jan 1st, 1970 at 00:00:00 UTC, aka the Unix Epoch.

read the millisecond timestamps

We read the timestamp from a date object:

d_2021.getTime() // 1,609,459,200,000 (ms)

We can read the current timestamp:

Date.now() // 1,777,109,775,765 (ms)

build a Date from a timestamp

We build a date from a given timestamp (or from the current one)

new Date(1_627_541_982_738) // 2021-07-29T06:59:42.738Z
new Date() // from current timestamp

compare dates

The difference between two timestamps, considered as an absolute value, represent the amount of time between both dates.

d_1971.getTime() - d_1970.getTime() // 31,536,000,000 (ms)

Note: if we try to subtract dates directly, it fails in TypeScript.

We can use the comparison operators on dates to check for posteriority:

d_2021 > d_2020 // true

(misc) console built-in date formatting

JavaScript consoles don't log dates as milliseconds as it's unreadable. They log dates in a calendar format:

  • The Node.js REPL use the standard ISO 8601 format (in the UTC time zone).
  • The browsers' console uses a lengthier format, using the device time zone.
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) // Chrome
earlymorning logo

JS Date API introduction

instants

JS Date objects represent and store instants (aka dates) as millisecond timestamps. The timestamp is the number of milliseconds since Jan 1st, 1970 at 00:00:00 UTC, aka the Unix Epoch.

read the millisecond timestamps

We read the timestamp from a date object:

d_2021.getTime() // 1,609,459,200,000 (ms)

We can read the current timestamp:

Date.now() // 1,777,109,775,765 (ms)

build a Date from a timestamp

We build a date from a given timestamp (or from the current one)

new Date(1_627_541_982_738) // 2021-07-29T06:59:42.738Z
new Date() // from current timestamp

compare dates

The difference between two timestamps, considered as an absolute value, represent the amount of time between both dates.

d_1971.getTime() - d_1970.getTime() // 31,536,000,000 (ms)

Note: if we try to subtract dates directly, it fails in TypeScript.

We can use the comparison operators on dates to check for posteriority:

d_2021 > d_2020 // true

(misc) console built-in date formatting

JavaScript consoles don't log dates as milliseconds as it's unreadable. They log dates in a calendar format:

  • The Node.js REPL use the standard ISO 8601 format (in the UTC time zone).
  • The browsers' console uses a lengthier format, using the device time zone.
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) // Chrome