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()
メソッドは value
や unit
を、この 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);
引数
解説
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 ago
や in 1 day
の代わりに yesterday
や tomorrow
の文字列が生成されます。これにより、出力に数値が含まれなくなることがあります。
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 GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
format |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- See implementation notes.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.