实现说明
fmt、d1、d2、d3 定义在模块顶层,中间不经过函数作用域。
使用要点
- 导入面(如果有的话)全在标准库内,随语言本身一起版本化。
- 直接运行文件,输出会带上标签,比如
same month :、cross month:、parts count:——输出的每一行都能指回产生它的那次调用。
常见问题
不安装任何包也能运行吗?
可以,开箱即跑——没有引用任何内建 API 之外的东西。 跨调用保留的状态放在这些顶层绑定里:fmt、d1、d2。
核心语句
.map((part) => `${part.source}:${part.type}=${JSON.stringify(part.value)}`);
const fmt = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC',
});
代码示例
const fmt = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC',
});
const d1 = Date.UTC(2026, 4, 10);
const d2 = Date.UTC(2026, 4, 14);
const d3 = Date.UTC(2026, 5, 2);
console.log('same month :', fmt.formatRange(d1, d2));
console.log('cross month:', fmt.formatRange(d1, d3));
// formatRangeToParts labels each token as 'shared', 'startRange', or 'endRange'
const summary = fmt
.formatRangeToParts(d1, d2)
.map((part) => `${part.source}:${part.type}=${JSON.stringify(part.value)}`);
console.log('parts count:', summary.length);
console.log('sample part:', summary[0], '|', summary[2], '|', summary[4]);