サンプル / ローカライズ
和暦・日付・深夜シフトの表示
元年表記を含む和暦、ゼロ埋めなしの年月日表記、日をまたぐ深夜シフトの時刻範囲をフォーマットします。
試してみよう
- 平成最後の日と令和初日をクリックし、2019年5月1日を境に
平成31年4月30日から令和元年5月1日へ切り替わることを確認します。 - 2026-05-01 を選び、月日のゼロ埋めを付けずに和暦が
令和8年と出力されることを確認します。 - 日をまたぐシフト時刻を編集し、
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' を明示的に渡します。内部の ISO 8601 日付を変更せずに和暦出力でき、改元初年は自動で 元年 表記になります。