如何将相对时间格式化为“昨天”或“1 天前”?

使用 numeric 选项来控制相对时间显示为“昨天”还是“1 天前”

简介

时间戳在现代 Web 应用中随处可见。例如,社交媒体帖子会显示“昨天发布”,而分析面板则显示“1 天前”。两者描述的是同一时间间隔,但表达方式带来的体验不同。前者更具对话感和自然感,后者则显得精确和正式。

JavaScript 通过 Intl.RelativeTimeFormat API 提供了对这种格式化选择的控制。你可以决定用户看到“昨天”这样的自然表达,还是“1 天前”这样的数字表达。这个决定会影响界面的正式或随和程度。

numeric 选项控制格式风格

Intl.RelativeTimeFormat 中,numeric 选项决定输出格式。该选项接受两个值。

当值为 auto 时,会在有自然语言表达时优先使用自然表达。当值为 always 时,始终使用数字表达。

const autoFormatter = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });
const alwaysFormatter = new Intl.RelativeTimeFormat('en-US', { numeric: 'always' });

这两种格式化方式在相同时间值下会产生不同的输出。

使用 auto 显示“昨天”和“明天”

当你希望使用自然语言表达时,将 numeric 设置为 auto。格式化器会在 day 值为 -1、0、1 时分别输出“昨天”、“今天”和“明天”。

const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });

rtf.format(-1, 'day');  // "yesterday"
rtf.format(0, 'day');   // "today"
rtf.format(1, 'day');   // "tomorrow"

当没有自然语言等价表达时,格式化器会自动切换为数字表达。

rtf.format(-2, 'day');  // "2 days ago"
rtf.format(2, 'day');   // "in 2 days"

这种方式会产生混合风格:常见时间引用使用自然语言,其他情况则用数字。

使用 always 始终显示数字值

当你需要一致的数字输出时,将 numeric 设置为 always。格式化器会对所有数值(包括 -1、0 和 1)生成数字表达。

const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'always' });

rtf.format(-1, 'day');  // "1 day ago"
rtf.format(0, 'day');   // "in 0 days"
rtf.format(1, 'day');   // "in 1 day"

当你省略 numeric 选项时,always 的值将作为默认值。

const rtf = new Intl.RelativeTimeFormat('en-US');
rtf.format(-1, 'day');  // "1 day ago"

该默认值可确保数字格式始终一致,除非你明确选择自然表达方式。

其他语言中的自然时间表达

不仅仅是英语,其他语言也有各自的自然时间表达。例如,法语用 "hier" 表示昨天,西班牙语用 "ayer",日语用 "昨日"。

const frenchRtf = new Intl.RelativeTimeFormat('fr', { numeric: 'auto' });
frenchRtf.format(-1, 'day');  // "hier"
frenchRtf.format(1, 'day');   // "demain"

const spanishRtf = new Intl.RelativeTimeFormat('es', { numeric: 'auto' });
spanishRtf.format(-1, 'day');  // "ayer"
spanishRtf.format(1, 'day');   // "mañana"

const japaneseRtf = new Intl.RelativeTimeFormat('ja', { numeric: 'auto' });
japaneseRtf.format(-1, 'day');  // "昨日"
japaneseRtf.format(1, 'day');   // "明日"

numeric 选项适用于所有语言环境。当你选择 auto 时,用户会看到本地语言的自然表达。当你选择 always 时,用户会看到本地语言的数字表达。

根据界面风格进行选择

正式界面适合使用 numeric: 'always'。分析仪表盘、系统日志和技术报告需要精确且一致的格式。数字值可在所有时间范围内提供这种精确性。

非正式界面适合使用 numeric: 'auto'。社交媒体动态、消息应用和社区论坛通过自然语言增强互动。像“昨天”“明天”这样的表达更具人情味。

请考虑整个界面的一致性。在同一应用的不同部分混用两种风格会造成混淆。用户期望时间戳在整个体验中遵循同一模式。

always 的默认值可带来最可预测的行为。当自然语言能提升你的界面体验时,请有意识地选择 auto