示例 / 本地化
韩语空格与合并范围
格式化带谚文单位空格的韩语日期、合并后的日期范围以及前置时段的 12 小时制时间。
动手试试
- 点击 +35 days 或在 Span 输入框中输入
35,观察范围跨入 6 月后结束日期自动补出6월。 - 点击 +4 days,查看
format()如何将共用的年月合并为2026년 5월 1일~5일。 - 将时间切到 09:30,观察小时前的韩语时段词从
오후切换为오전。
import { configure, date, time } from 'native-dates';
configure({ locale: 'ko' });
const dayInput = document.querySelector('#day');
const span = document.querySelector('#span');
const clock = document.querySelector('#clock');
const output = document.querySelector('#output');
function render() {
const length = Number(span.value);
if (!dayInput.value || !clock.value || !(length >= 1)) { return; }
const day = date(dayInput.value);
const range = day.to(day.plus(length, 'days'));
const periodClock = time(clock.value).format({ hour: 'numeric', minute: '2-digit', hour12: true });
const rows = [
['Full date', ".format('full')", day.format('full')],
['Collapsed range', ".format('long')", range.format('long')],
['Clock with period', 'hour12: true', periodClock],
['Month heading', '.yearMonth.text', day.yearMonth.text],
];
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-span]')) {
button.addEventListener('click', () => {
span.value = button.dataset.span;
render();
});
}
dayInput.addEventListener('input', render);
span.addEventListener('input', render);
clock.addEventListener('input', render);
render();
正在启动…
实现原理
与中文和日语不同,韩语正字法要求在年、月、日单位之后各留一个空格。调用一次 configure({ locale: 'ko' }),即可在所有 .text 属性和 format() 调用中统一应用该空格规则。
调用 range.format('long') 会用波浪号连接起止日期并合并共用的年月,同时在两个日期数字后都保留 일;当范围跨入下个月时,结束日期的月份单位会自动重新显示。
韩语 12 小时制将上午或下午时段词置于小时数字之前。读取 day.yearMonth.text 则可生成不带日单位(일)的简洁月份标题。