Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Intl.RelativeTimeFormat.prototype.format() — format relative time

Turn a signed time offset and an explicit unit into localized display text. The method formats an offset you supply; it does not calculate the difference between dates.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const formatter = new Intl.RelativeTimeFormat(locales, options);
formatter.format(value, unit);

Intl.RelativeTimeFormat.prototype.format is an instance method. Call formatter.format(value, unit) to get a string using the formatter’s resolved locale and the options set at construction. Your application computes the offset from a reference point and chooses the unit; the method does not read the clock or subtract dates.

Negative values mean the past and positive values mean the future. When a numeric pattern is used, -0 selects the past pattern and +0 selects the future pattern. unit accepts the exact identifiers "second", "minute", "hour", "day", "week", "month", "quarter", and "year", as well as their forms ending in s. The identifier’s form does not dictate the grammar of the output.

numeric: "always" (the default) uses a numeric pattern. numeric: "auto" uses a dedicated phrase when available, such as yesterday, and otherwise falls back to a numeric pattern. style selects "long" (the default), "short", or "narrow". Runtime support varies, and text can differ even for the same locale, for example by using non-breaking spaces. Do not compare the result to hardcoded text in portable tests.

The method requires a formatter instance as this; calling a detached method without a valid this throws TypeError. Use formatter.format.bind(formatter) if you need a callback. After checking this, the method applies ToNumber to value, then ToString to unit. For example, a BigInt as value throws TypeError. After conversion, NaN, Infinity, -Infinity, or an unsupported unit identifier causes a RangeError.

Examples

{
  const numeric = new Intl.RelativeTimeFormat("en", { numeric: "always" });
  const auto = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
  const past = numeric.format(-1, "day");
  console.log(past);
  console.log(auto.format(-1, "day"));
  console.log(past === numeric.format(-1, "days"));
}

Result

1 day ago
yesterday
true

For the same offset of `-1` day, the first two lines show typical English text for `"always"` and `"auto"`. The third line shows that `"day"` and `"days"` are equivalent.

Related lessons

  • JavaScript · Lesson 24 · Advanced · Version: 4

Sources