Sub topic 1
Why Temporal Exists: What Goes Wrong with Date
Prerequisites
This chapter assumes you know ES2015+ syntax, objects and exceptions, ES module imports, and the basics of the legacy Date object. You also need Node.js or a browser to run the examples.
What Goes Wrong with Date
A Date value is a single timestamp that also behaves like a calendar date. That double role causes these common bugs:
- Months are zero-based, so
new Date(2024, 2, 15)means March 15. - A
Datecan only use UTC or the host's local time zone, so you cannot represent "9:00 in Tokyo" directly. - Setters change the object in place.
- String parsing differs between formats.
'2024-03-15'is read as UTC, while'2024-03-15T00:00'is read as local time.
const d = new Date(2024, 0, 31); // January 31
d.setMonth(1); // mutates d
console.log(d.getMonth()); // 2: it rolled over to March 2Running Temporal Today
Some runtimes ship Temporal natively, and others still need the polyfill (npm install @js-temporal/polyfill). The examples below assume this setup:
import { Temporal as TemporalPolyfill } from '@js-temporal/polyfill';
const Temporal = globalThis.Temporal ?? TemporalPolyfill;
console.log(Temporal.Now.plainDateISO().toString());A Map of the Types
Temporal separates two kinds of time:
- Exact time is one point on the global timeline.
- Wall-clock time is what a calendar or clock on the wall shows.
ZonedDateTime connects the two by pairing an exact time with a time zone.
| Need | Type |
|---|---|
| Log timestamp | `Instant` |
| Meeting in a city | `ZonedDateTime` |
| Birthday | `PlainDate` or `PlainMonthDay` |
| Store opening hour | `PlainTime` |
Immutable by Design
Methods such as add and with return a new object and leave the original unchanged. That makes Temporal values safe to share between functions.
Reading the Current Time
Temporal.Now gives you the current time as whichever type you need:
console.log(Temporal.Now.instant().toString());
console.log(Temporal.Now.zonedDateTimeISO().toString());
console.log(Temporal.Now.plainDateISO().toString());Plain Types, Creation, and Parsing
Plain types carry no time zone. You can create them from an ISO 8601 string, from constructor arguments, or from a property bag (a plain object of fields). Months are numbered from 1.
const date = Temporal.PlainDate.from('2024-03-15');
const sameDate = new Temporal.PlainDate(2024, 3, 15);
const fromBag = Temporal.PlainDate.from({ year: 2024, month: 3, day: 15 });
console.log(date.equals(sameDate)); // true
console.log(fromBag.toString()); // '2024-03-15'
console.log(date.dayOfWeek); // 5 (Friday; Monday is 1)Exercise
You need to store a recurring anniversary that has no year, such as "December 25". Which Temporal type fits, and how do you create it?
Show answer
Use PlainMonthDay, for example Temporal.PlainMonthDay.from('12-25') or Temporal.PlainMonthDay.from({ month: 12, day: 25 }).