Sub topic 19
Formatting Dates and Times for Display
This chapter assumes you can already create Temporal values with from() and that you know the difference between Plain types, Instant, and ZonedDateTime. It also assumes basic familiarity with Intl.DateTimeFormat from legacy Date code. The examples use a global Temporal. If your runtime lacks one, use the polyfill fallback from the runtime support chapter.
Temporal gives you two formatting paths. Use toString() when a machine reads the output. Use toLocaleString() or Intl.DateTimeFormat when a person reads it.
Choosing a Formatting Method
Machine-Readable Output with toString
Every Temporal type has a toString() method that returns an ISO 8601 string. The time-bearing types accept options that control precision and which annotations appear in the string.
const zdt = Temporal.ZonedDateTime.from(
'2024-03-15T21:00:00.123456+09:00[Asia/Tokyo]'
);
console.log(zdt.toString());
// '2024-03-15T21:00:00.123456+09:00[Asia/Tokyo]'
console.log(zdt.toString({ smallestUnit: 'minute' }));
// '2024-03-15T21:00+09:00[Asia/Tokyo]'
console.log(zdt.toString({ fractionalSecondDigits: 3 }));
// '2024-03-15T21:00:00.123+09:00[Asia/Tokyo]'
console.log(zdt.toString({ timeZoneName: 'never' }));
// '2024-03-15T21:00:00.123456+09:00'
const date = Temporal.PlainDate.from('2024-03-15');
console.log(date.toString({ calendarName: 'always' }));
// '2024-03-15[u-ca=iso8601]'| Option | Applies to | Values | Effect |
|---|---|---|---|
| `smallestUnit` | time-bearing types | `'minute'`, `'second'`, `'millisecond'`, ... | Truncates or rounds to that unit |
| `fractionalSecondDigits` | time-bearing types | `'auto'`, 0–9 | Fixed number of fractional digits |
| `roundingMode` | time-bearing types | `'trunc'` (default), `'halfExpand'`, ... | How dropped digits are handled |
| `offset` | `ZonedDateTime` | `'auto'`, `'never'` | Shows or hides the `+09:00` offset |
| `timeZoneName` | `ZonedDateTime` | `'auto'`, `'never'`, `'critical'` | Shows or hides `[Asia/Tokyo]` |
| `calendarName` | date-bearing types | `'auto'`, `'always'`, `'never'`, `'critical'` | Shows or hides `[u-ca=...]` |
Human-Readable Output with toLocaleString
toLocaleString(locales, options) takes the same arguments as Intl.DateTimeFormat. Each type formats only the fields it actually has.
const date = Temporal.PlainDate.from('2024-03-15');
console.log(date.toLocaleString('en-US', { dateStyle: 'long' }));
// 'March 15, 2024'
console.log(date.toLocaleString('de-DE', { dateStyle: 'full' }));
// 'Freitag, 15. März 2024'
const time = Temporal.PlainTime.from('14:05');
console.log(time.toLocaleString('en-US', { timeStyle: 'short' }));
// '2:05 PM'
const tokyo = Temporal.ZonedDateTime.from('2024-03-15T21:00[Asia/Tokyo]');
console.log(
tokyo.toLocaleString('en-US', {
dateStyle: 'medium',
timeStyle: 'short',
timeZoneName: 'short',
})
);
// 'Mar 15, 2024, 9:00 PM GMT+9'How each type treats time zones
The rules for time zones differ by type, and this is where most formatting bugs appear:
- Plain types have no time zone, so the formatter never converts them. A
PlainTimeof14:05prints as 2:05 PM in every zone. - Instant has no wall-clock time of its own. The formatter shows it in the
timeZoneoption, or in the system zone if you leave that out. - ZonedDateTime always formats in its own time zone. Passing a
timeZoneoption throws aTypeError. To display it in a different zone, convert it withwithTimeZone()first.
const instant = Temporal.Instant.from('2024-03-15T12:00:00Z');
console.log(
instant.toLocaleString('en-US', { timeZone: 'Europe/Paris', timeStyle: 'short' })
);
// '1:00 PM'
const tokyo = Temporal.ZonedDateTime.from('2024-03-15T21:00[Asia/Tokyo]');
try {
tokyo.toLocaleString('en-US', { timeZone: 'Europe/Paris' });
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(
tokyo.withTimeZone('Europe/Paris').toLocaleString('en-US', { timeStyle: 'short' })
);
// '1:00 PM'Reusing Intl.DateTimeFormat
Creating a formatter is expensive compared with calling format(). When you render many values, such as a table column, build one formatter and reuse it. format(), formatToParts(), and formatRange() all accept Temporal objects.
const fmt = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' });
const start = Temporal.PlainDate.from('2024-03-15');
const end = Temporal.PlainDate.from('2024-03-20');
console.log(fmt.format(start)); // 'Mar 15, 2024'
console.log(fmt.formatRange(start, end)); // 'Mar 15 – 20, 2024'
const parts = fmt.formatToParts(start);
console.log(parts.find((p) => p.type === 'month').value); // 'Mar'formatRange() requires both arguments to be the same Temporal type. Mixing a PlainDate with a PlainDateTime throws a TypeError.
Common Errors
Options that share no fields with the value
If none of the requested fields exist on the value, formatting throws a TypeError. A PlainDate has no hour, so this fails:
const date = Temporal.PlainDate.from('2024-03-15');
try {
date.toLocaleString('en-US', { timeStyle: 'short' });
} catch (e) {
console.log(e instanceof TypeError); // true
}When options partly overlap the value's fields, the formatter ignores the fields that don't apply.
PlainYearMonth and PlainMonthDay calendar mismatch
A PlainDate in the ISO calendar is formatted in the locale's calendar without trouble. A PlainYearMonth or PlainMonthDay is different. Its calendar must match the formatter's calendar exactly, otherwise formatting throws a RangeError. These types cannot be converted between calendars, because a month or a month-day has no single day to convert. Values parsed from strings like '2024-03' use iso8601, while en-US formats in gregory.
const isoMonth = Temporal.PlainYearMonth.from('2024-03');
try {
isoMonth.toLocaleString('en-US', { year: 'numeric', month: 'long' });
} catch (e) {
console.log(e instanceof RangeError); // true
}
const gregMonth = Temporal.PlainYearMonth.from({
year: 2024,
month: 3,
calendar: 'gregory',
});
console.log(gregMonth.toLocaleString('en-US', { year: 'numeric', month: 'long' }));
// 'March 2024'Using locale strings as data
A string like '3/15/2024' is ambiguous across locales, and its exact format depends on ICU. Store and exchange toString() output. Use localized strings only for display.
Exercise
You have const zdt = Temporal.ZonedDateTime.from('2024-07-04T18:30[America/New_York]') and you want to show it to a user in London as a short time. Why does zdt.toLocaleString('en-GB', { timeZone: 'Europe/London', timeStyle: 'short' }) fail, and what should you write instead?
Show answer
A ZonedDateTime always formats in its own time zone, so passing a timeZone option throws a TypeError. Convert it first: zdt.withTimeZone('Europe/London').toLocaleString('en-GB', { timeStyle: 'short' }), which prints '23:30'.
Exercise
A report renders 5,000 PlainDate values with new Intl.DateTimeFormat('fr-FR', { dateStyle: 'long' }).format(d) inside the loop. What change improves performance, and would the same approach work if the values were ZonedDateTime objects?
Show answer
Create the formatter once outside the loop and call its format method for each value. That approach would not work for ZonedDateTime, because format throws a TypeError for that type. Either call toInstant() on each value and use one formatter created with the right timeZone option, or call toLocaleString on each value.
Exercise
Write a toString call that turns 2024-03-15T09:41:27.889-04:00[America/New_York] into '2024-03-15T09:42-04:00[America/New_York]'.
Show answer
zdt.toString({ smallestUnit: 'minute', roundingMode: 'halfExpand' }). The default roundingMode, 'trunc', would produce 09:41.