日付と時間フィールドのローカライズされたラベルを表示するにはどうすればよいですか?
Intl.DisplayNamesを使用してフィールドラベルを取得し、Intl.DateTimeFormatを使用して任意の言語で月名と曜日名を取得します。
はじめに
日付と時刻の入力フォームを構築する際、各フィールドを説明するラベルが必要です。日付ピッカーには「月」、「年」、「日」などのラベルが必要です。時刻ピッカーには「時」や「分」などのラベルが必要です。これらのラベルはユーザーの言語で表示される必要があります。
これらのラベルを英語でハードコーディングすると、国際的なアプリケーションでは機能しません。フランス語のユーザーは「Mois」や「Année」の表示を期待し、スペイン語のユーザーは「Mes」や「Año」を探します。どの言語でも自動的にこれらのラベルを提供するシステムが必要です。
JavaScriptはこのために2つの補完的なAPIを提供しています。Intl.DisplayNames APIは「月」や「年」などのフィールドラベルを提供します。Intl.DateTimeFormat APIは月名や曜日名などのフィールドの実際の値を提供します。
日付と時刻のフィールドラベルを理解する
日付と時刻のインターフェースには2種類のラベルが必要です。フィールドラベルは各入力に入るデータの種類を説明します。フィールド値はドロップダウンやピッカーに表示される実際のデータです。
フィールドラベルには「年」、「月」、「日」、「時」、「分」、「秒」などの単語が含まれます。これらはフォームフィールド自体にラベルを付けます。
フィールド値には「1月」や「2月」などの月名、「月曜日」や「火曜日」などの曜日名、「午前」や「午後」などの期間ラベルが含まれます。これらはドロップダウンや選択リストに表示されます。
完全な日付フォームには両方のタイプのラベルが必要です。
<label>月</label>
<select>
<option>1月</option>
<option>2月</option>
<option>3月</option>
<!-- その他の月 -->
</select>
<label>年</label>
<input type="number" />
「月」と「1月」の両方がローカライズを必要としますが、それぞれ異なるアプローチが必要です。
Intl.DisplayNamesでフィールドラベルを取得する
type: "dateTimeField"を指定したIntl.DisplayNamesコンストラクタは、日付と時刻のコンポーネントのローカライズされたラベルを返します。
const labels = new Intl.DisplayNames('en-US', { type: 'dateTimeField' });
console.log(labels.of('year'));
// "year"
console.log(labels.of('month'));
// "month"
console.log(labels.of('day'));
// "day"
console.log(labels.of('hour'));
// "hour"
console.log(labels.of('minute'));
// "minute"
console.log(labels.of('second'));
// "second"
of()メソッドはフィールドコードを受け取り、そのローカライズされたラベルを返します。ラベルは指定されたロケールの規則に一致します。
ロケールを変更することで、任意の言語でラベルを取得できます。
// スペイン語のラベル
const esLabels = new Intl.DisplayNames('es-ES', { type: 'dateTimeField' });
console.log(esLabels.of('year'));
// "año"
console.log(esLabels.of('month'));
// "mes"
console.log(esLabels.of('day'));
// "día"
console.log(esLabels.of('hour'));
// "hora"
console.log(esLabels.of('minute'));
// "minuto"
// フランス語のラベル
const frLabels = new Intl.DisplayNames('fr-FR', { type: 'dateTimeField' });
console.log(frLabels.of('year'));
// "année"
console.log(frLabels.of('month'));
// "mois"
console.log(frLabels.of('day'));
// "jour"
console.log(frLabels.of('hour'));
// "heure"
console.log(frLabels.of('minute'));
// "minute"
// 日本語のラベル
const jaLabels = new Intl.DisplayNames('ja-JP', { type: 'dateTimeField' });
console.log(jaLabels.of('year'));
// "年"
console.log(jaLabels.of('month'));
// "月"
console.log(jaLabels.of('day'));
// "日"
console.log(jaLabels.of('hour'));
// "時"
console.log(jaLabels.of('minute'));
// "分"
各ロケールは独自の言語と文字でラベルを提供します。
利用可能な日付と時刻のフィールドコード
Intl.DisplayNames APIは以下のフィールドコードをサポートしています。
const labels = new Intl.DisplayNames('en-US', { type: 'dateTimeField' });
console.log(labels.of('era'));
// "era"
console.log(labels.of('year'));
// "year"
console.log(labels.of('quarter'));
// "quarter"
console.log(labels.of('month'));
// "month"
console.log(labels.of('weekOfYear'));
// "week"
console.log(labels.of('weekday'));
// "day of the week"
console.log(labels.of('day'));
// "day"
console.log(labels.of('dayPeriod'));
// "AM/PM"
console.log(labels.of('hour'));
// "hour"
console.log(labels.of('minute'));
// "minute"
console.log(labels.of('second'));
// "second"
console.log(labels.of('timeZoneName'));
// "time zone"
これらのコードを使用して、インターフェースに必要な日付や時刻のコンポーネントのラベルを取得できます。
ローカライズされた月名の取得
Intl.DateTimeFormat APIは、ドロップダウンや選択リストに表示する月名を提供します。monthオプションを"long"に設定してフォーマッターを作成し、各月を表す日付をフォーマットします。
function getMonthNames(locale) {
const formatter = new Intl.DateTimeFormat(locale, {
month: 'long',
timeZone: 'UTC'
});
const months = [];
for (let month = 0; month < 12; month++) {
const date = new Date(Date.UTC(2000, month, 1));
months.push(formatter.format(date));
}
return months;
}
console.log(getMonthNames('en-US'));
// ["January", "February", "March", "April", "May", "June",
// "July", "August", "September", "October", "November", "December"]
この関数は年の各月の日付を作成し、それをフォーマットして月名を抽出します。timeZone: 'UTC'を設定することで、タイムゾーンに関係なく一貫した結果を確保します。
どの言語でも月名を取得できます。
console.log(getMonthNames('es-ES'));
// ["enero", "febrero", "marzo", "abril", "mayo", "junio",
// "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
console.log(getMonthNames('fr-FR'));
// ["janvier", "février", "mars", "avril", "mai", "juin",
// "juillet", "août", "septembre", "octobre", "novembre", "décembre"]
console.log(getMonthNames('ja-JP'));
// ["1月", "2月", "3月", "4月", "5月", "6月",
// "7月", "8月", "9月", "10月", "11月", "12月"]
各ロケールは、それぞれの慣習に従って月名をフォーマットします。
月名の長さを制御する
month オプションは月名の長さを制御するさまざまな値を受け付けます。
"long" 値は月の完全な名前を返します。
const longFormatter = new Intl.DateTimeFormat('en-US', {
month: 'long',
timeZone: 'UTC'
});
const date = new Date(Date.UTC(2000, 0, 1));
console.log(longFormatter.format(date));
// "January"
"short" 値は省略された月名を返します。
const shortFormatter = new Intl.DateTimeFormat('en-US', {
month: 'short',
timeZone: 'UTC'
});
console.log(shortFormatter.format(date));
// "Jan"
"narrow" 値は可能な限り最短の月名を返し、通常は1文字です。
const narrowFormatter = new Intl.DateTimeFormat('en-US', {
month: 'narrow',
timeZone: 'UTC'
});
console.log(narrowFormatter.format(date));
// "J"
"narrow" は複数の月が同じ文字を共有する可能性があるため、慎重に使用してください。英語では、1月、6月、7月はすべて「J」になります。
ローカライズされた曜日名を取得する
曜日名を取得するには同じパターンを使用します。フォーマットを制御するには weekday オプションを設定します。
function getWeekdayNames(locale, format = 'long') {
const formatter = new Intl.DateTimeFormat(locale, {
weekday: format,
timeZone: 'UTC'
});
const weekdays = [];
// 日曜日から開始(2000年1月2日は日曜日でした)
for (let day = 0; day < 7; day++) {
const date = new Date(Date.UTC(2000, 0, 2 + day));
weekdays.push(formatter.format(date));
}
return weekdays;
}
console.log(getWeekdayNames('en-US'));
// ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
console.log(getWeekdayNames('en-US', 'short'));
// ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
console.log(getWeekdayNames('en-US', 'narrow'));
// ["S", "M", "T", "W", "T", "F", "S"]
どの言語でも曜日名を取得できます。
console.log(getWeekdayNames('es-ES'));
// ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"]
console.log(getWeekdayNames('fr-FR'));
// ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"]
console.log(getWeekdayNames('ja-JP'));
// ["日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日"]
異なるロケールでは週の開始日が異なる場合があります。この関数は常に日曜日から土曜日の順に返します。
ローカライズされた時間帯ラベルを取得する
時間帯ラベルとは、12時間制で使用されるAMとPMの表示です。formatToParts()を使用してこれらのラベルを抽出します。
function getPeriodLabels(locale) {
const formatter = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
hour12: true,
timeZone: 'UTC'
});
const amDate = new Date(Date.UTC(2000, 0, 1, 0, 0, 0));
const pmDate = new Date(Date.UTC(2000, 0, 1, 12, 0, 0));
const amParts = formatter.formatToParts(amDate);
const pmParts = formatter.formatToParts(pmDate);
const am = amParts.find(part => part.type === 'dayPeriod').value;
const pm = pmParts.find(part => part.type === 'dayPeriod').value;
return { am, pm };
}
console.log(getPeriodLabels('en-US'));
// { am: "AM", pm: "PM" }
console.log(getPeriodLabels('es-ES'));
// { am: "a. m.", pm: "p. m." }
console.log(getPeriodLabels('fr-FR'));
// { am: "AM", pm: "PM" }
console.log(getPeriodLabels('ja-JP'));
// { am: "午前", pm: "午後" }
formatToParts()メソッドは、フォーマットされた時間の各部分を表すオブジェクトの配列を返します。type: "dayPeriod"を持つオブジェクトには、AMまたはPMのラベルが含まれています。
一部のロケールではデフォルトで24時間制を使用し、時間帯ラベルを含みません。hour12: trueオプションを使用して12時間制を強制することができます。
完全にローカライズされた日付フォームを構築する
これらのテクニックをすべて組み合わせて、完全にローカライズされた日付入力フォームを作成します。
function createDateForm(locale) {
const fieldLabels = new Intl.DisplayNames(locale, { type: 'dateTimeField' });
const monthNames = getMonthNames(locale);
const currentYear = new Date().getFullYear();
return {
monthLabel: fieldLabels.of('month'),
months: monthNames.map((name, index) => ({
value: index + 1,
label: name
})),
dayLabel: fieldLabels.of('day'),
yearLabel: fieldLabels.of('year'),
yearPlaceholder: currentYear
};
}
// 前の例からのヘルパー関数
function getMonthNames(locale) {
const formatter = new Intl.DateTimeFormat(locale, {
month: 'long',
timeZone: 'UTC'
});
const months = [];
for (let month = 0; month < 12; month++) {
const date = new Date(Date.UTC(2000, month, 1));
months.push(formatter.format(date));
}
return months;
}
const enForm = createDateForm('en-US');
console.log(enForm.monthLabel);
// "month"
console.log(enForm.months[0]);
// { value: 1, label: "January" }
console.log(enForm.dayLabel);
// "day"
console.log(enForm.yearLabel);
// "year"
const esForm = createDateForm('es-ES');
console.log(esForm.monthLabel);
// "mes"
console.log(esForm.months[0]);
// { value: 1, label: "enero" }
console.log(esForm.dayLabel);
// "día"
console.log(esForm.yearLabel);
// "año"
この構造は、HTMLでローカライズされた日付フォームをレンダリングするために必要なすべてを提供します。
function renderDateForm(locale) {
const form = createDateForm(locale);
return `
<div class="date-form">
<div class="form-field">
<label>${form.monthLabel}</label>
<select name="month">
${form.months.map(month =>
`<option value="${month.value}">${month.label}</option>`
).join('')}
</select>
</div>
<div class="form-field">
<label>${form.dayLabel}</label>
<input type="number" name="day" min="1" max="31" />
</div>
<div class="form-field">
<label>${form.yearLabel}</label>
<input type="number" name="year" placeholder="${form.yearPlaceholder}" />
</div>
</div>
`;
}
console.log(renderDateForm('en-US'));
// 英語のラベルと月名でフォームをレンダリング
console.log(renderDateForm('fr-FR'));
// フランス語のラベルと月名でフォームをレンダリング
フォームは指定したどのロケールにも自動的に適応します。
ローカライズされた時間フォームを構築する
同じアプローチを適用して、時、分、および時間帯セレクタを持つ時間入力フォームを作成します。
function createTimeForm(locale) {
const fieldLabels = new Intl.DisplayNames(locale, { type: 'dateTimeField' });
const periods = getPeriodLabels(locale);
const hours = [];
for (let hour = 1; hour <= 12; hour++) {
hours.push({ value: hour, label: hour.toString() });
}
const minutes = [];
for (let minute = 0; minute < 60; minute += 5) {
minutes.push({
value: minute,
label: minute.toString().padStart(2, '0')
});
}
return {
hourLabel: fieldLabels.of('hour'),
hours: hours,
minuteLabel: fieldLabels.of('minute'),
minutes: minutes,
periodLabel: fieldLabels.of('dayPeriod'),
periods: [
{ value: 'am', label: periods.am },
{ value: 'pm', label: periods.pm }
]
};
}
// 前の例のヘルパー関数
function getPeriodLabels(locale) {
const formatter = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
hour12: true,
timeZone: 'UTC'
});
const amDate = new Date(Date.UTC(2000, 0, 1, 0, 0, 0));
const pmDate = new Date(Date.UTC(2000, 0, 1, 12, 0, 0));
const amParts = formatter.formatToParts(amDate);
const pmParts = formatter.formatToParts(pmDate);
const am = amParts.find(part => part.type === 'dayPeriod').value;
const pm = pmParts.find(part => part.type === 'dayPeriod').value;
return { am, pm };
}
const enTime = createTimeForm('en-US');
console.log(enTime.hourLabel);
// "hour"
console.log(enTime.minuteLabel);
// "minute"
console.log(enTime.periodLabel);
// "AM/PM"
console.log(enTime.periods);
// [{ value: "am", label: "AM" }, { value: "pm", label: "PM" }]
const jaTime = createTimeForm('ja-JP');
console.log(jaTime.hourLabel);
// "時"
console.log(jaTime.minuteLabel);
// "分"
console.log(jaTime.periodLabel);
// "午前/午後"
console.log(jaTime.periods);
// [{ value: "am", label: "午前" }, { value: "pm", label: "午後" }]
これにより、ローカライズされた時間選択ツールをレンダリングするために必要なすべてのデータが提供されます。
日付と時刻のフィールドラベルを使用するタイミング
日付と時刻のフィールドラベルは、いくつかのタイプのインターフェースに表示されます。
カスタム日付と時刻ピッカー
日付ピッカー、カレンダーウィジェット、または時間セレクターを構築する際にローカライズされたラベルを使用します。
const locale = navigator.language;
const labels = new Intl.DisplayNames(locale, { type: 'dateTimeField' });
const datePicker = {
yearLabel: labels.of('year'),
monthLabel: labels.of('month'),
dayLabel: labels.of('day')
};
フォームフィールドラベル
日付と時刻データの標準フォーム入力にラベルを適用します。
const labels = new Intl.DisplayNames('en-US', { type: 'dateTimeField' });
document.querySelector('#birthdate-month-label').textContent =
labels.of('month');
document.querySelector('#birthdate-year-label').textContent =
labels.of('year');
アクセシビリティラベル
スクリーンリーダーや支援技術のためにローカライズされたARIAラベルを提供します。
const locale = navigator.language;
const labels = new Intl.DisplayNames(locale, { type: 'dateTimeField' });
const input = document.querySelector('#date-input');
input.setAttribute('aria-label', labels.of('year'));
データテーブルヘッダー
日付と時刻コンポーネントを表示するテーブルの列にラベルを付けます。
const labels = new Intl.DisplayNames('en-US', { type: 'dateTimeField' });
const table = `
<table>
<thead>
<tr>
<th>${labels.of('year')}</th>
<th>${labels.of('month')}</th>
<th>${labels.of('day')}</th>
</tr>
</thead>
</table>
`;
ブラウザサポート
type: "dateTimeField"を使用したIntl.DisplayNames APIは、2022年3月以降の主要ブラウザでサポートされています。
ChromeとEdgeはバージョン99からサポートしています。Firefoxはバージョン99からサポートしています。Safariはバージョン15.4からサポートしています。
使用する前に、この機能が利用可能かどうかを確認できます。
function supportsDateTimeFieldLabels() {
try {
const labels = new Intl.DisplayNames('en', { type: 'dateTimeField' });
labels.of('year');
return true;
} catch (error) {
return false;
}
}
if (supportsDateTimeFieldLabels()) {
const labels = new Intl.DisplayNames('en-US', { type: 'dateTimeField' });
console.log(labels.of('month'));
} else {
console.log('month'); // 英語へのフォールバック
}
古いブラウザでは、フォールバックラベルを提供する必要があります。一般的なフィールド用の簡単なマッピングオブジェクトを作成します。
const fallbackLabels = {
en: {
year: 'year',
month: 'month',
day: 'day',
hour: 'hour',
minute: 'minute',
second: 'second'
},
es: {
year: 'año',
month: 'mes',
day: 'día',
hour: 'hora',
minute: 'minuto',
second: 'segundo'
},
fr: {
year: 'année',
month: 'mois',
day: 'jour',
hour: 'heure',
minute: 'minute',
second: 'seconde'
}
};
function getFieldLabel(field, locale) {
if (supportsDateTimeFieldLabels()) {
const labels = new Intl.DisplayNames(locale, { type: 'dateTimeField' });
return labels.of(field);
}
const language = locale.split('-')[0];
return fallbackLabels[language]?.[field] || fallbackLabels.en[field];
}
console.log(getFieldLabel('month', 'es-ES'));
// "mes" (サポートされている場合はAPIから、そうでない場合はフォールバックから)
これにより、すべてのブラウザでフォームが機能し、利用可能な場合はネイティブのローカライゼーションを活用できます。
月名と曜日名を取得するためのIntl.DateTimeFormat APIは、Internet Explorer 11およびすべての最新ブラウザまで遡って、より広くサポートされています。ほとんどの場合、機能検出なしで使用できます。