JS Temporal API
In this page:
Why Temporal Exists
The built-in Date object has several well-known design flaws: it's mutable so any code holding a reference can change it unexpectedly, months are zero-indexed so January is 0, and it conflates a moment in time with how that moment is displayed in a timezone. Temporal is a modern date-time API designed to fix these issues with a family of precise, immutable types.
Example: Why Temporal Exists
const d = new Date(2024, 0, 15); // month 0 = January
console.log(d.getMonth()); // 0, not 1
// Temporal fixes this with explicit, immutable types
Temporal.PlainDate
Temporal.PlainDate represents a calendar date, like a birthday, with no time-of-day or timezone information attached at all. This separation matters because many real-world dates genuinely don't need a specific moment in time, and forcing one onto them, as the old Date object does, invites timezone bugs.
Example: Temporal.PlainDate
const date = Temporal.PlainDate.from("2024-06-15");
console.log(date.toString()); // no time or timezone attached
Temporal.PlainTime and PlainDateTime
Temporal.PlainTime represents a time of day, like 2:30 PM, with no associated date, while Temporal.PlainDateTime combines both a calendar date and a time of day but still without any timezone. Splitting these concerns lets code state exactly what kind of value it's working with instead of always needing a full timezone-aware timestamp.
Example: Temporal.PlainTime and PlainDateTime
const time = Temporal.PlainTime.from("14:30");
const dateTime = Temporal.PlainDateTime.from("2024-06-15T14:30");
console.log(time.toString(), dateTime.toString());
Temporal.Now
Temporal.Now provides several methods for getting the current moment, including instant() for a precise point in time and plainDateISO() for just today's calendar date in the ISO calendar. Splitting now into these specific forms makes it explicit exactly what kind of current-time value your code actually needs.
Example: Temporal.Now
const now = Temporal.Now.instant();
const today = Temporal.Now.plainDateISO();
console.log(now.toString(), today.toString());
Comparing Temporal to Date
Every Temporal type is immutable, so operations like add() or subtract() always return a new object instead of modifying the original, eliminating an entire category of aliasing bugs that plague the legacy Date object. Temporal also requires you to be explicit about timezones through types like ZonedDateTime, rather than silently mixing local and UTC interpretations the way Date does.
Example: Comparing Temporal to Date
const date = Temporal.PlainDate.from("2024-01-01");
const later = date.add({ days: 10 }); // returns a new object
console.log(date.toString(), later.toString()); // original unchanged
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: