JavaScript Intl.RelativeTimeFormat 实战:从“昨天”到负零与夏令时边界
消息列表里的“昨天”、任务卡片上的“2小时后”,看起来像日期计算,其实包含两项不同工作:先决定相差多少、采用什么单位,再把结果表达成用户熟悉的语言。Intl.RelativeTimeFormat 负责后半项。如果把单位选择、取整甚至时区计算也交给它,界面可能没有报错,却显示了错误含义。

本文于北京时间2026年10月24日验证,实际环境为 Node.js 24.19.0、ICU 78.3、CLDR 48.0、时区数据2026b。下面十个文件均可独立运行,不需安装依赖。五个反例通过断言证明错误预期与结果不符,全部退出码为0、标准错误为空,并非五次程序运行失败。中文措辞与标点属于本环境实测,不承诺所有浏览器逐字相同。
一、auto 选择自然说法,不负责自动换单位
先把输入理解为一对数据:有方向的数量,以及已经确定的单位。负数通常描述过去,正数描述未来。numeric 默认为 always;auto 在当前语言存在相应自然表达时使用它,否则仍然输出数字短语。其分支规则可对照 ECMA-402 第13版的格式化算法,具体中文词语则以下面的实测为准。
正确示例1:比较两种文案策略
保存为 01_correct_numeric.cjs,运行 node 01_correct_numeric.cjs。
const assert = require('node:assert/strict');
const auto = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'auto' });
const always = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'always' });
const values = [-1, 0, 1, 3];
const a = values.map(n => auto.format(n, 'day'));
const b = values.map(n => always.format(n, 'day'));
assert.deepEqual(a, ['昨天', '今天', '明天', '3天后']);
assert.deepEqual(b, ['1天前', '0天后', '1天后', '3天后']);
console.log('auto:', a.join(' | '));
console.log('always:', b.join(' | '));
实际标准输出:
auto: 昨天 | 今天 | 明天 | 3天后 always: 1天前 | 0天后 | 1天后 | 3天后
同样的日数既可以显示“昨天”,也可以显示“1天前”。活动记录偏自然语言、审计列表偏统一数字,是产品取舍,不存在必须选 auto 的通用答案。注意第四项仍是“3天后”,auto 不等于把所有数字替换成词语。
错误假设反例1:90秒会自动变成分钟
保存为 01_counter_auto_unit.cjs,运行 node 01_counter_auto_unit.cjs。
const assert = require('node:assert/strict');
const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });
const actual = rtf.format(90, 'second');
const assumed = 'in 1.5 minutes';
assert.equal(actual, 'in 90 seconds');
assert.notEqual(actual, assumed);
console.log('错误预期:', assumed);
console.log('实际输出:', actual);
实际标准输出:
错误预期: in 1.5 minutes 实际输出: in 90 seconds
实际仍使用传入的 second。若产品要显示分钟,应在业务层先换算、选择精度,再把分钟数交给格式器;不要因为一个选项叫 auto,就推断它会执行没有约定过的单位策略。
二、负零也有方向,取整后不要只检查小于零
正确示例2:明确过去、未来及零的表现
保存为 02_correct_signed_zero.cjs,运行 node 02_correct_signed_zero.cjs。
const assert = require('node:assert/strict');
const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'always' });
assert.equal(rtf.format(-3, 'day'), '3 days ago');
assert.equal(rtf.format(2, 'day'), 'in 2 days');
assert.equal(rtf.format(-0, 'second'), '0 seconds ago');
assert.equal(rtf.format(0, 'second'), 'in 0 seconds');
console.log(rtf.format(-3, 'day'));
console.log(rtf.format(2, 'day'));
console.log('-0:', rtf.format(-0, 'second'));
console.log('+0:', rtf.format(0, 'second'));
实际标准输出:
3 days ago in 2 days -0: 0 seconds ago +0: in 0 seconds
负零不是为了炫技才出现:一个略小于零的时间差经过 Math.trunc 就可能产生它。下面先把负0.4截断,再用常见的小于零判断拼接文案;结果与格式器不同。这个测试适合放在“刚刚”边界的回归用例中,而不是等用户发现时间方向跳变。
错误假设反例2:只用 value 小于0就能复刻方向
保存为 02_counter_zero_direction.cjs,运行 node 02_counter_zero_direction.cjs。
const assert = require('node:assert/strict');
const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'always' });
const value = Math.trunc(-0.4);
assert.ok(Object.is(value, -0));
const naive = value < 0 ? '0 seconds ago' : 'in 0 seconds';
const actual = rtf.format(value, 'second');
assert.notEqual(naive, actual);
console.log('value < 0:', value < 0);
console.log('错误预期:', naive);
console.log('实际输出:', actual);
实际标准输出:
value < 0: false 错误预期: in 0 seconds 实际输出: 0 seconds ago
如果需求规定零统一显示“刚刚”,应在调用前处理整个零区间,并写清阈值;如果需要保留过去方向,则不要随手归一化负零。auto 还可能直接返回自然词语,所以这里特意固定 always 隔离方向问题。业务层的显示策略和数值表示应分别测试。
三、单位是有限集合,narrow 也不是长度承诺
可用单位为 second、minute、hour、day、week、month、quarter、year,也接受这些词的复数形式。millisecond 不在集合内;NaN 与正负无穷也不能作为有效相对量。下面验证单位别名和异常,同时展示英文小时的三种样式。
正确示例3:验证单位与样式
保存为 03_correct_units_styles.cjs,运行 node 03_correct_units_styles.cjs。
const assert = require('node:assert/strict');
const units = ['second', 'minute', 'hour', 'day',
'week', 'month', 'quarter', 'year'];
const rtf = new Intl.RelativeTimeFormat('en-US');
for (const unit of units) {
assert.equal(rtf.format(2, unit), rtf.format(2, unit + 's'));
}
assert.throws(() => rtf.format(1, 'millisecond'), RangeError);
for (const value of [NaN, Infinity, -Infinity]) {
assert.throws(() => rtf.format(value, 'day'), RangeError);
}
console.log('八种单位的单复数形式等价');
for (const style of ['long', 'short', 'narrow']) {
const f = new Intl.RelativeTimeFormat('en-US', { style });
console.log(style + ':', f.format(-2, 'hour'));
}
console.log('不支持的单位及非有限值均抛出 RangeError');
实际标准输出:
八种单位的单复数形式等价 long: 2 hours ago short: 2 hr. ago narrow: 2h ago 不支持的单位及非有限值均抛出 RangeError
style 的 long、short、narrow 是语言数据中的表达风格,不是一个字符串裁剪器。英文小时在本环境明显缩短,不意味着中文、所有单位或每次版本升级都保持同样关系。紧凑卡片仍需要布局溢出测试,不能用选项名称代替实际宽度测量。
错误假设反例3:narrow 一定比 long 更短
保存为 03_counter_narrow_length.cjs,运行 node 03_counter_narrow_length.cjs。
const assert = require('node:assert/strict');
const long = new Intl.RelativeTimeFormat('zh-CN', { style: 'long' });
const narrow = new Intl.RelativeTimeFormat('zh-CN', { style: 'narrow' });
const a = long.format(2, 'day');
const b = narrow.format(2, 'day');
assert.equal(a, b);
assert.equal(b.length < a.length, false);
console.log('long:', a);
console.log('narrow:', b);
console.log('narrow 必然更短:', b.length < a.length);
实际标准输出:
long: 2天后 narrow: 2天后 narrow 必然更短: false
四、显式指定语言,再区分“支持请求”和“最终配置”
服务端和客户端若依赖各自默认语言,可能生成不同文案。建议明确传入语言列表,检查 supportedLocalesOf 的返回值,并读取 resolvedOptions 观察最终配置。Node.js 24.19.0 官方国际化文档说明 ICU 数据可因构建方式不同而变化,因此不能把一台开发机的语言能力直接推广到所有部署环境。
正确示例4:在当前环境验证中英文支持
保存为 04_correct_locale.cjs,运行 node 04_correct_locale.cjs。
const assert = require('node:assert/strict');
const requested = ['zh-CN', 'en-US'];
const supported = Intl.RelativeTimeFormat.supportedLocalesOf(
requested, { localeMatcher: 'lookup' }
);
assert.deepEqual(supported, requested);
const rtf = new Intl.RelativeTimeFormat(supported[0], {
localeMatcher: 'lookup', numeric: 'auto'
});
assert.equal(rtf.resolvedOptions().locale, 'zh-CN');
assert.equal(rtf.format(-1, 'day'), '昨天');
console.log('支持的请求:', JSON.stringify(supported));
console.log('实际配置:', JSON.stringify(rtf.resolvedOptions()));
console.log(rtf.format(-1, 'day'));
实际标准输出:
支持的请求: ["zh-CN","en-US"]
实际配置: {"locale":"zh-CN","style":"long","numeric":"auto","numberingSystem":"latn"}
昨天
这里的断言有意要求当前运行环境支持两种语言,属于部署检查,不是通用回退函数。若检查结果为空,应走应用明确约定的备用展示,而不是继续取数组首项,让 undefined 悄悄变成使用运行时默认语言。
错误假设反例4:支持列表就是实际解析后的 locale
保存为 04_counter_supported_resolved.cjs,运行 node 04_counter_supported_resolved.cjs。
const assert = require('node:assert/strict');
const tag = 'en-US-u-ca-gregory';
const supported = Intl.RelativeTimeFormat.supportedLocalesOf(
[tag], { localeMatcher: 'lookup' }
)[0];
const resolved = new Intl.RelativeTimeFormat(tag, {
localeMatcher: 'lookup'
}).resolvedOptions().locale;
assert.equal(supported, tag);
assert.equal(resolved, 'en-US');
assert.notEqual(supported, resolved);
console.log('supportedLocalesOf:', supported);
console.log('resolvedOptions.locale:', resolved);
实际标准输出:
supportedLocalesOf: en-US-u-ca-gregory resolvedOptions.locale: en-US
例子使用真实的日历扩展 ca-gregory,并未猜测一个“不支持的语言”。请求可被支持,但这个扩展不会让相对短语格式器开始计算公历日期。支持列表保留的请求标识,与实例采用的 locale 不是同一类结果;排错时应把两者一起记录。
五、需要高亮数字时使用 parts,不要拆字符串
把输出按空格切开,再假设第一段就是数字,会绑死某一种语言顺序。formatToParts 给出结构化片段,保留原顺序拼接即可还原完整文本。下面特意用带分组和小数的数值,避免只验证一个整数就误以为数字永远是单一片段。
正确示例5:同时处理数字短语与纯文字结果
保存为 05_correct_parts.cjs,运行 node 05_correct_parts.cjs。
const assert = require('node:assert/strict');
const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });
const parts = rtf.formatToParts(-1234.5, 'day');
assert.equal(parts.map(p => p.value).join(''), rtf.format(-1234.5, 'day'));
assert.ok(parts.some(p => p.type === 'group'));
assert.ok(parts.some(p => p.type === 'fraction'));
assert.ok(parts.filter(p => p.type !== 'literal').every(p => p.unit === 'day'));
const word = rtf.formatToParts(-1, 'day');
assert.deepEqual(word, [{ type: 'literal', value: 'yesterday' }]);
console.log(JSON.stringify(parts));
console.log(JSON.stringify(word));
实际标准输出:
[{"type":"integer","value":"1","unit":"day"},{"type":"group","value":",","unit":"day"},{"type":"integer","value":"234","unit":"day"},{"type":"decimal","value":".","unit":"day"},{"type":"fraction","value":"5","unit":"day"},{"type":"literal","value":" days ago"}]
[{"type":"literal","value":"yesterday"}]
数字片段可能含 integer、group、decimal、fraction;本例这些片段带有 unit,而 literal 不带。第二次调用只有 yesterday 这个 literal,没有可高亮的数字。因此渲染逻辑要允许“零个数字片段”,并用文本节点承载片段内容,不应把格式化结果当作可执行 HTML。
六、最后一个反例:日历上的明天不总是24小时后
RelativeTimeFormat 不是时间戳差值计算器,也不是把时长拆成天、小时、分钟的工具。先问清“天”的含义:已经经过的固定24小时,还是指定时区里的日历日期差?下面是纽约2026年3月8日至9日两个本地午夜。日期前进一天,但本环境时区数据验证它们只相隔23小时。
错误假设反例5:毫秒差除以86400000就是日历天数
保存为 05_counter_calendar_day.cjs,运行 node 05_counter_calendar_day.cjs。
const assert = require('node:assert/strict');
const start = new Date('2026-03-08T00:00:00-05:00');
const end = new Date('2026-03-09T00:00:00-04:00');
const date = new Intl.DateTimeFormat('en-CA', {
timeZone: 'America/New_York', calendar: 'gregory',
year: 'numeric', month: '2-digit', day: '2-digit'
});
const key = value => {
const parts = date.formatToParts(value);
return ['year', 'month', 'day']
.map(type => parts.find(p => p.type === type).value).join('-');
};
assert.equal(key(start), '2026-03-08');
assert.equal(key(end), '2026-03-09');
const hours = (end - start) / 3600000;
const naiveDays = Math.floor((end - start) / 86400000);
assert.equal(hours, 23);
assert.equal(naiveDays, 0);
const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });
assert.notEqual(rtf.format(naiveDays, 'day'), rtf.format(1, 'day'));
console.log('纽约日历日期:', key(start), '->', key(end));
console.log('经过小时:', hours);
console.log('除以固定 24 小时再向下取整:', naiveDays);
console.log('错误的日历标签:', rtf.format(naiveDays, 'day'));
console.log('本例日历标签:', rtf.format(1, 'day'));
实际标准输出:
纽约日历日期: 2026-03-08 -> 2026-03-09 经过小时: 23 除以固定 24 小时再向下取整: 0 错误的日历标签: today 本例日历标签: tomorrow
向下取整得到0,再交给格式器便显示 today;要求日历标签时,本例应采用1而得到 tomorrow。代码中的1仅代表已经核实的这两个相邻日期,并不是通用日期差算法。月末、跨年、夏令时结束以及其他日历都需要另行设计;也不能把 month 固定换成30天来覆盖“下个月”。
上线前的最小检查
把这项能力拆成三层会更可靠:计算层决定参照时刻、时区和日历;策略层选择单位、舍入与“刚刚”阈值;展示层只接收数量与单位并生成本地化短语。测试至少覆盖未来与过去、正负零、单位切换阈值、自然词语、分组小数和跨日边界。固定语言及选项可复用同一个格式器,但缓存键必须包含会影响输出的配置。
本文断言用于复现这次环境;升级 Node 或 ICU 后若措辞改变,先核对语言数据和实际配置,不要直接判定日期算法出错。反过来,即便所有字符串快照都通过,也不能证明上游时间差计算正确。让计算规则与显示文本拥有各自的测试,才是相对时间界面长期稳定的关键。
规范依据:ECMA-402 第13版第18章,其中构造选项、单位归一化、负零分支与分段输出是接口规则;本文展示的具体语言字符串、语言支持与夏令时样例均由上述 Node 环境实际执行验证。没有进行全浏览器兼容性测试。

