如何将相对时间格式化为“昨天”或“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。格式化器会为 -1、0 和 1 的天数值生成“昨天”、“今天”和“明天”。
const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });
rtf.format(-1, 'day'); // "昨天"
rtf.format(0, 'day'); // "今天"
rtf.format(1, 'day'); // "明天"
当没有自然语言等价时,格式化器会切换到数字表达。
rtf.format(-2, 'day'); // "2 天前"
rtf.format(2, 'day'); // "2 天后"
这会创建一种混合样式,其中常见的时间参考使用自然语言,而不常见的时间参考使用数字。
始终使用以显示数值
当您希望输出一致的数值时,将 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'。社交媒体动态、消息应用和社区论坛通过自然语言创造联系。像 "yesterday" 和 "tomorrow" 这样的表达更具人情味。
请考虑整个界面的风格一致性。在同一应用程序的不同部分混合使用两种风格会造成混淆。用户期望时间戳在整个体验中遵循相同的模式。
默认值 always 提供了最可预测的行为。当自然语言能增强特定界面时,请有意识地选择 auto。