Sub topic 7
Creating and Parsing Temporal Values
This chapter assumes you know modern JavaScript syntax, how exceptions work, and how to get a Temporal global, either natively or through the polyfill set up in the runtime chapter. You should also know the difference between the Plain types and Instant from the type overview.
Every Temporal type gives you two ways to create a value. You can call the constructor with exact numeric fields, or you can call the static from() method. from() accepts an ISO 8601 string, a property bag (a plain object holding fields), or another Temporal object. These paths validate input in different ways, and the differences cause most creation bugs.
Three Ways to Build the Same Value
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)Months start at 1. Legacy Date numbers months from 0, so new Date(2024, 3, 15) is April 15. In Temporal, new Temporal.PlainDate(2024, 3, 15) is March 15. Check this first when you port Date code.
dayOfWeek is a computed property. You never pass it in. Temporal derives it from the fields you supplied.
Constructors: Strict and Numeric
Constructors take positional numbers in a fixed order and reject anything out of range.
const time = new Temporal.PlainTime(9, 30); // 09:30:00
const dt = new Temporal.PlainDateTime(2024, 3, 15, 9, 30);
try {
new Temporal.PlainDate(2024, 2, 30);
} catch (e) {
console.log(e instanceof RangeError); // true
}Instant and ZonedDateTime constructors take epoch nanoseconds as a BigInt, not calendar fields:
const epoch = new Temporal.Instant(0n);
console.log(epoch.toString()); // '1970-01-01T00:00:00Z'
const zoned = new Temporal.ZonedDateTime(0n, 'Asia/Tokyo');
console.log(zoned.toString()); // '1970-01-01T09:00:00+09:00[Asia/Tokyo]'Passing a regular number such as 0 throws a TypeError. For millisecond values, use Temporal.Instant.fromEpochMilliseconds(ms).
In application code, use constructors only when the numbers are already known to be valid. Use from() for everything else.
Parsing ISO 8601 Strings
from() parses a strict subset of ISO 8601 and RFC 9557, the format with a bracketed time zone. Unlike Date.parse, it never guesses. A string that does not match the format throws a RangeError, and so does a string that names an impossible date.
for (const s of ['2024-03-15', '2024-02-30', 'March 15, 2024']) {
try {
console.log(Temporal.PlainDate.from(s).toString());
} catch (e) {
console.log(`${s}: ${e.constructor.name}`);
}
}
// '2024-03-15'
// '2024-02-30: RangeError'
// 'March 15, 2024: RangeError'Each type requires certain parts of the string and treats others as optional:
| Type | Example string | Notes |
|---|---|---|
| `PlainDate` | `2024-03-15` | A time part is allowed and ignored |
| `PlainTime` | `09:30:15.250` | Seconds and fractions are optional |
| `PlainDateTime` | `2024-03-15T09:30` | A space can replace `T` |
| `PlainYearMonth` | `2024-03` | |
| `PlainMonthDay` | `03-15` or `--03-15` | |
| `Instant` | `2024-03-15T12:00Z` | Requires `Z` or a numeric offset |
| `ZonedDateTime` | `2024-03-15T12:00+01:00[Europe/Paris]` | Requires a bracketed time zone |
The rules follow from what each type means:
// Plain types accept richer strings and drop what they don't model
const d = Temporal.PlainDate.from('2024-03-15T10:30:00+01:00[Europe/Paris]');
console.log(d.toString()); // '2024-03-15'
// Instant needs an exact point in time
try {
Temporal.Instant.from('2024-03-15T12:00');
} catch (e) {
console.log(e instanceof RangeError); // true: no offset, so no exact time
}
// Plain types reject Z, because Z marks an exact time, not a wall-clock reading
try {
Temporal.PlainDateTime.from('2024-03-15T12:00Z');
} catch (e) {
console.log(e instanceof RangeError); // true
}The Z rejection is deliberate. A UTC timestamp parsed into a PlainDateTime would silently lose its meaning. When you actually want the UTC wall-clock fields, say so in code: Temporal.Instant.from(s).toZonedDateTimeISO('UTC').toPlainDateTime().
Strings can also carry a calendar annotation such as [u-ca=hebrew]. The non-ISO calendars chapter covers that.
Property Bags
A property bag is an ordinary object whose keys match the type's field names. You need it when the values come from form inputs or database columns.
const t = Temporal.PlainTime.from({ hour: 9 });
console.log(t.toString()); // '09:00:00' (missing time fields default to 0)
const ym = Temporal.PlainYearMonth.from({ year: 2024, month: 3 });
console.log(ym.toString()); // '2024-03'
try {
Temporal.PlainDate.from({ year: 2024, month: 3 }); // no day
} catch (e) {
console.log(e instanceof TypeError); // true
}Time fields default to zero. Date fields have no defaults, and a missing required date field throws a TypeError. Each type has its own field names, so { hours: 9 }, with the plural, does nothing in PlainTime.from and produces midnight. Duration is the type that uses plural names.
You can use monthCode (for example 'M03') in place of month. If you pass both, they must agree. Month codes matter most in calendars with leap months.
Bags Constrain by Default
Bags and constructors disagree on out-of-range values. By default, from() with a bag clamps the value to the nearest valid one:
const clamped = Temporal.PlainDate.from({ year: 2023, month: 2, day: 30 });
console.log(clamped.toString()); // '2023-02-28'
try {
Temporal.PlainDate.from({ year: 2023, month: 2, day: 30 }, { overflow: 'reject' });
} catch (e) {
console.log(e instanceof RangeError); // true
}Passing Temporal Objects to from()
from() also accepts another Temporal object. For the same type, it returns a new, equal object. For a related type, it converts the value when the conversion is unambiguous:
const dt = Temporal.PlainDateTime.from('2024-03-15T09:30');
const copy = Temporal.PlainDateTime.from(dt);
console.log(copy === dt, copy.equals(dt)); // false true
const dateOnly = Temporal.PlainDate.from(dt);
console.log(dateOnly.toString()); // '2024-03-15'So a function that starts with Temporal.PlainDate.from(input) can accept a string, a bag, or a Temporal object, and always gets a validated PlainDate.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Date is one month late | Ported 0-based months from `Date` | Use 1-based months |
| `TypeError` from a constructor for `Instant` | Passed a number, not a `BigInt` | Use `0n` or `fromEpochMilliseconds` |
| `RangeError` parsing an API timestamp into a Plain type | String ends in `Z` | Parse as `Instant`, then convert |
| Invalid day silently changed | Bag with default `constrain` | Pass `{ overflow: 'reject' }` |
| Time is midnight unexpectedly | Plural field names in bag | Use `hour`, `minute`, `second` |
Exercise
What does each line print or throw? (a) Temporal.PlainDate.from('2024-04-31') (b) Temporal.PlainDate.from({ year: 2024, month: 4, day: 31 }).toString() (c) new Temporal.PlainDate(2024, 4, 31)
Show answer
(a) throws RangeError, because strings with impossible dates are always rejected. (b) prints '2024-04-30', because property bags constrain by default. (c) throws RangeError, because constructors never constrain.
Exercise
An API returns '2024-11-25T08:00:00Z'. You need the calendar date in UTC as a PlainDate. Why does Temporal.PlainDate.from(s) fail, and what should you write instead?
Show answer
Plain types reject the Z designator, so that an exact UTC time is not reinterpreted as a wall-clock reading by accident. Write Temporal.Instant.from(s).toZonedDateTimeISO('UTC').toPlainDate(), which gives '2024-11-25'.
Exercise
Write a function parseBirthday(fields) that accepts { year, month, day } from a form and returns a PlainDate, throwing on invalid days instead of adjusting them.
Show answer
function parseBirthday(fields) { return Temporal.PlainDate.from({ year: Number(fields.year), month: Number(fields.month), day: Number(fields.day) }, { overflow: 'reject' }); } A missing field throws TypeError and an out-of-range day throws RangeError.