native-dates

示例 / 本地化

日语年号、日期与跨夜班次

格式化以“元年”标识首年的日本年号和历、不补零的汉字日期,以及跨午夜的夜班时钟时间范围。

动手试试

  1. 点击 平成最後の日 和 令和初日,观察日期如何从 平成31年4月30日 跨入 2019 年 5 月 1 日的 令和元年5月1日。
  2. 选择 2026-05-01,查看和历如何推进到 令和8年,同时月日数字保持不补零。
  3. 将班次时间调整为跨午夜,观察 timeRange() 如何保持纯时钟时间范围并使用日语波浪号 ~ 连接。
import { configure, date, timeRange } from 'native-dates';

configure({ locale: 'ja' });

const dayInput = document.querySelector('#day');
const start = document.querySelector('#start');
const end = document.querySelector('#end');
const output = document.querySelector('#output');

function render() {
  if (!dayInput.value || !start.value || !end.value) { return; }
  const day = date(dayInput.value);
  const span = day.to(day.plus(4, 'days'));
  const shift = timeRange(start.value, end.value);

  const rows = [
    ['Full date', ".format('full')", day.format('full')],
    ['Month heading', '.yearMonth.text', day.yearMonth.text],
    ['Date span', '.text', span.text],
    ['Overnight shift', '.text', shift.text],
    ['Imperial era', 'ja-u-ca-japanese', day.format('long', 'ja-u-ca-japanese')],
  ];

  output.innerHTML = rows.map(([label, locale, value]) => `
    <li>
      <span class="label">${label} <code>${locale}</code></span>
      <b>${value}</b>
    </li>`).join('');
}

for (const button of document.querySelectorAll('[data-date]')) {
  button.addEventListener('click', () => {
    dayInput.value = button.dataset.date;
    render();
  });
}

dayInput.addEventListener('input', render);
start.addEventListener('input', render);
end.addEventListener('input', render);
render();

正在启动…

实现原理

调用一次 configure({ locale: 'ja' }),所有文本预览和格式预设都会切换为日语。标准预设以不补零的数字搭配“年”“月”“日”单位,而 day.yearMonth 则省略“日”以生成月份标题。

日期范围和跨午夜的 timeRange() 会自动读取同一全局区域设置,使用日语波浪号连接起止端点,跨午夜时也不会强行拼凑虚构的日历日期。

只有在需要切换到其他历法时才单独传入区域标签。传入 'ja-u-ca-japanese' 会按日本和历格式化,并在每个年号的第一年输出 元年。