Intl.DateTimeFormat.prototype.formatRange()

Intl.DateTimeFormat.prototype.formatRange() は、 Intl.DateTimeFormat オブジェクトがインスタンス化されたときに提供された localeoptions に基づいて、もっとも簡明な方法で日付の範囲を書式化します。

試してみましょう

構文

js
formatRange(startDate, endDate);

基本的な formatRange の使用

このメソッドは 2 つの Date を受け取り、 Intl.DateTimeFormat オブジェクトがインスタンス化されたときに提供された localeoptions に基づいて日付の範囲を書式化します。

js
let date1 = new Date(Date.UTC(2007, 0, 10, 10, 0, 0));
let date2 = new Date(Date.UTC(2007, 0, 10, 11, 0, 0));
let date3 = new Date(Date.UTC(2007, 0, 20, 10, 0, 0));
// > 'Wed, 10 Jan 2007 10:00:00 GMT'
// > 'Wed, 10 Jan 2007 11:00:00 GMT'
// > 'Sat, 20 Jan 2007 10:00:00 GMT'

let fmt1 = new Intl.DateTimeFormat("en", {
  year: "2-digit",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
});
console.log(fmt1.format(date1));
console.log(fmt1.formatRange(date1, date2));
console.log(fmt1.formatRange(date1, date3));
// > '1/10/07, 10:00 AM'
// > '1/10/07, 10:00 – 11:00 AM'
// > '1/10/07, 10:00 AM – 1/20/07, 10:00 AM'

let fmt2 = new Intl.DateTimeFormat("en", {
  year: "numeric",
  month: "short",
  day: "numeric",
});
console.log(fmt2.format(date1));
console.log(fmt2.formatRange(date1, date2));
console.log(fmt2.formatRange(date1, date3));
// > 'Jan 10, 2007'
// > 'Jan 10, 2007'
// > 'Jan 10 – 20, 2007'

仕様書

Specification
ECMAScript Internationalization API Specification
# sec-intl.datetimeformat.prototype.formatRange

ブラウザーの互換性

BCD tables only load in the browser

関連情報