实现说明
launch、en、de、parts 定义在模块顶层,中间不经过函数作用域。
使用要点
- 跑完文件,输出里会留下标记——
en-US :、de-DE :、parts :。
常见问题
它依赖第三方库吗?
没有引用任何第三方库,标准库就够了。 状态都挂在模块顶层:launch、en、de。
核心语句
const parts = en.formatToParts(launch).filter((p) => p.type !== 'literal');
const en = new Intl.DateTimeFormat('en-US', {
dateStyle: 'long',
timeStyle: 'short',
timeZone: 'UTC',
});
const de = new Intl.DateTimeFormat('de-DE', {
dateStyle: 'long',
timeStyle: 'short',
timeZone: 'UTC',
});
代码示例
// Intl.DateTimeFormat: 日期渲染规则交给区域设置,而不是手写格式串
const launch = new Date('2026-03-14T09:30:00Z');
const en = new Intl.DateTimeFormat('en-US', {
dateStyle: 'long',
timeStyle: 'short',
timeZone: 'UTC',
});
console.log('en-US :', en.format(launch));
const de = new Intl.DateTimeFormat('de-DE', {
dateStyle: 'long',
timeStyle: 'short',
timeZone: 'UTC',
});
console.log('de-DE :', de.format(launch));
// formatToParts: 拿到字段分段,自定义组装
const parts = en.formatToParts(launch).filter((p) => p.type !== 'literal');
console.log('parts :', parts.map((p) => p.type + '=' + p.value).join(' '));
// formatRange: 同日的两个时刻自动省略重复部分
const end = new Date('2026-03-14T17:00:00Z');
console.log('range :', en.formatRange(launch, end));