CKTIS / JavaScript
Intl.DateTimeFormat.prototype.format — format dates and times for a locale
Use `formatter.format()` to display a date and time for a locale and time zone. The result is text for people to read, not a format for storing data.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const formatter = new Intl.DateTimeFormat(locales, options);
formatter.format(date);
formatter.format();
const format = formatter.format;
format(date);Call formatter.format(...) on an Intl.DateTimeFormat instance, not on the constructor. Create a formatter with new Intl.DateTimeFormat(locales, options) to choose a locale, a time zone, and the fields to display. The call returns a string and does not change the Date object. If you omit locales or timeZone, the formatter uses the corresponding runtime default.
In ECMA-402 (2024), pass a Date or a numeric timestamp in milliseconds since the Unix epoch, not seconds. Omitting the argument or passing undefined formats the current instant at call time. format() does not parse date strings: convert the text to a valid Date or timestamp first. An invalid Date, NaN, infinity, or a timestamp outside the Date range throws RangeError.
Intl.DateTimeFormat.prototype.format is a getter property. Reading formatter.format returns the same function bound to that instance, so you can pass it directly as a callback, as in dates.map(formatter.format), without calling bind().
Runtimes with Temporal integration can also format Temporal.PlainDateTime, Temporal.PlainDate, Temporal.PlainTime, Temporal.PlainYearMonth, or Temporal.PlainMonthDay when the type is compatible with the formatter's settings. Temporal.ZonedDateTime throws TypeError; use Temporal.ZonedDateTime.prototype.toLocaleString() to format it in its own time zone.
Even with the same settings, the output can vary across runtimes, including spaces, punctuation, and bidirectional control characters. Do not compare it with hard-coded text or use it as a data exchange format.
Examples
const formatter = new Intl.DateTimeFormat("en-GB", {
year: "numeric",
month: "long",
day: "numeric",
timeZone: "UTC",
});
const date = new Date("2024-06-15T00:00:00Z");
const format = formatter.format;
const text = formatter.format(date);
console.log(typeof text);
console.log(text === format(date.getTime()));Result
string true
The example fixes the instant, locale, and UTC time zone. It checks the result type and that the detached function formats a timestamp the same way as an instance call with the equivalent `Date`, without assuming the exact text.
Related lessons
- JavaScript · Lesson 15 · Basic · Version: 4