← 中文资源

简体中文版本

DateTimeFormat.formatRange 智能折叠日期区间

用 Intl.DateTimeFormat.formatRange 格式化起止时间跨度,自动折叠同月或同年的重复部分,并用 formatRangeToParts 区分共享与起止片段。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

same month : May 10 – 14, 2026
cross month: May 10 – Jun 2, 2026
parts count: 7
sample part: shared:month="May" | startRange:day="10" | endRange:day="14"

实现说明

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]);