Intl.RelativeTimeFormat.prototype.format()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.

Intl.RelativeTimeFormat.prototype.format() メソッドは valueunit を、この Intl.RelativeTimeFormat オブジェクトのロケールと整形オプションに従って整形します。

試してみましょう

const rtf1 = new Intl.RelativeTimeFormat("en", { style: "short" });

console.log(rtf1.format(3, "quarter"));
// Expected output: "in 3 qtrs."

console.log(rtf1.format(-1, "day"));
// Expected output: "1 day ago"

console.log(rtf1.format(10, "seconds"));
// Expected output: "in 10 sec."

構文

js
relativeTimeFormat.format(value, unit);

引数

value

国際化された相対時間のメッセージに使用する数値です。

unit

国際化された相対時間のメッセージに使用する単位です。利用可能な値は、 "year", "quarter", "month", "week", "day", "hour", "minute", "second" です。複数形も許容されています。

解説

format ゲッター関数は、この Intl.RelativeTimeFormat オブジェクトのロケールと整形オプションに従って値や単位を整形し、文字列に格納します。

基本的な format の使い方

以下の例は、英語を使用した相対時間のフォーマッターの生成方法を示しています。

js
// ロケールで既定値を明確に指定して
// 相対時間フォーマッターを作成
const rtf = new Intl.RelativeTimeFormat("en", {
  localeMatcher: "best fit", // other values: "lookup"
  numeric: "always", // other values: "auto"
  style: "long", // other values: "short" or "narrow"
});

// 負の値 (-1) を使った相対時間の書式化
rtf.format(-1, "day");
// > "1 day ago"

// 正の値 (1) を使った相対時間の書式化
rtf.format(1, "day");
// > "in 1 day"

auto オプションの使用

numeric:auto オプションが渡された場合は、 1 day agoin 1 day の代わりに yesterdaytomorrow の文字列が生成されます。これにより、出力に数値が含まれなくなることがあります。

js
// ロケールで既定値を明確に指定して
// 相対時間フォーマッターを作成
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

// 負の値 (-1) を使った相対時間の書式化
rtf.format(-1, "day");
// > "yesterday"

// 正の値 (1) を使った相対時間の書式化
rtf.format(1, "day");
// > "tomorrow"

仕様書

Specification
ECMAScript® 2025 Internationalization API Specification
# sec-Intl.RelativeTimeFormat.prototype.format

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
format

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
See implementation notes.

関連情報