如何为日期和时间字段显示本地化标签?

使用 Intl.DisplayNames 获取字段标签,使用 Intl.DateTimeFormat 获取任意语言的月份和星期名称。

简介

在构建日期和时间输入表单时,需要为每个字段提供描述性标签。日期选择器需要像“月”、“年”、“日”这样的标签,时间选择器则需要“时”和“分”。这些标签必须以用户的语言显示。

将这些标签硬编码为英文不适用于国际化应用。法国用户期望看到“月”(Mois)和“年”(Année),而西班牙用户则希望看到“月”(Mes)和“年”(Año)。你需要一个能够自动为任意语言提供这些标签的系统。

JavaScript 提供了两套互补的 API。Intl.DisplayNames API 可用于获取“月”、“年”等字段标签。Intl.DateTimeFormat API 则可用于获取这些字段的实际值,如月份名称和星期名称。

理解日期和时间字段标签

日期和时间界面需要两类标签。字段标签用于描述每个输入框需要填写的数据类型。字段值则是下拉菜单和选择器中实际显示的数据。

字段标签包括“年”、“月”、“日”、“时”、“分”、“秒”等词,用于标注表单字段本身。

字段值包括“January”、“February”等月份名称,“Monday”、“Tuesday”等星期名称,以及“AM”、“PM”等时间段标签,这些用于填充下拉菜单和选择列表。

一个完整的日期表单需要这两类标签。

<label>Month</label>
<select>
  <option>January</option>
  <option>February</option>
  <option>March</option>
  <!-- more months -->
</select>

<label>Year</label>
<input type="number" />

“月”和“January”都需要本地化,但它们的处理方式不同。

使用 Intl.DisplayNames 获取字段标签

通过 Intl.DisplayNames 构造函数和 type: "dateTimeField" 参数,可以获取日期和时间组件的本地化标签。

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() 方法接收一个字段代码并返回其本地化标签。该标签符合指定语言环境的习惯。

只需更改 locale,即可获取任意语言的标签。

// Spanish labels
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"

// French labels
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"

// Japanese labels
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" 值会返回最短的月份名称,通常为单个字母。

const narrowFormatter = new Intl.DateTimeFormat('en-US', {
  month: 'narrow',
  timeZone: 'UTC'
});

console.log(narrowFormatter.format(date));
// "J"

请谨慎使用 "narrow",因为多个月份可能会使用相同的字母。在英文中,January、June 和 July 都会生成 "J"。

获取本地化的星期名称

使用相同的模式获取星期名称。设置 weekday 选项以控制格式。

function getWeekdayNames(locale, format = 'long') {
  const formatter = new Intl.DateTimeFormat(locale, {
    weekday: format,
    timeZone: 'UTC'
  });

  const weekdays = [];
  // Start from a Sunday (January 2, 2000 was a Sunday)
  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
  };
}

// Helper function from previous example
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'));
// Renders form with English labels and month names

console.log(renderDateForm('fr-FR'));
// Renders form with French labels and month names

该表单会自动适配你指定的任何本地化环境。

构建本地化时间表单

采用相同方法,创建包含小时、分钟和时间段选择器的时间输入表单。

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 }
    ]
  };
}

// Helper function from previous example
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>
`;

浏览器支持

自 2022 年 3 月起,主流浏览器已支持 Intl.DisplayNames API 及 type: "dateTimeField"

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'); // Fallback to English
}

对于旧版浏览器,需要提供备用标签。为常用字段创建一个简单的映射对象。

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" (from API if supported, from fallback otherwise)

这样可以确保你的表单在所有浏览器中都能正常工作,并在支持时利用原生本地化功能。

用于获取月份和星期名称的 Intl.DateTimeFormat API 兼容性更广,早在 Internet Explorer 11 及所有现代浏览器中就已支持。在大多数情况下可以直接使用,无需特性检测。