实现说明
顶层就这几处状态:now、later、fmt、rel。
使用要点
- 直接运行文件,输出会带上标签,比如
de-DE:、relative:、past:——输出的每一行都能指回产生它的那次调用。
常见问题
需要安装第三方包吗?
不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 文件的状态由几个模块级绑定持有:now、later、fmt。
核心语句
const parts = new Intl.ListFormat('en', { type: 'unit', style: 'short' });
const rel = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const fmt = new Intl.DateTimeFormat('de-DE', {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'UTC',
});
代码示例
const now = new Date('2026-11-17T12:00:00Z');
const later = new Date('2026-11-17T15:30:00Z');
// 绝对时间:语言标签决定顺序与格式
const fmt = new Intl.DateTimeFormat('de-DE', {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'UTC',
});
console.log('de-DE:', fmt.format(later));
// 相对时间:按单位与数值生成短语
const rel = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const diffMinutes = Math.round((later - now) / 60000);
console.log('relative:', rel.format(diffMinutes, 'minute'));
console.log('past:', rel.format(-2, 'day'));
// 时长分片:把毫秒拆成小时与分钟
const h = Math.floor(diffMinutes / 60);
const m = diffMinutes % 60;
const parts = new Intl.ListFormat('en', { type: 'unit', style: 'short' });
console.log('parts:', parts.format([`${h} hr`, `${m} min`]));