格式化相对时间
显示“2 天前”而不是时间戳
问题
应用程序会显示类似“发表于 2 天前”这样的时间戳。虽然这在英文中很清楚,但“2 天前”与“2 天后”(过去与将来)的逻辑和语法在不同语言中差异很大。简单地将字符串拼接(例如 '2' + ' ' + '天前')无法生成语法正确的输出。
解决方案
请使用专用组件,如 FormattedRelativeTime,来自 react-intl。该组件接收一个数值(例如 -2)和一个单位(如 'day'),并自动将其格式化为符合本地语言习惯、语法正确的字符串,例如“2 天前”、“hace 2 días”或“gestern”(昨天)。
步骤
1. 创建用于相对时间的客户端组件
必须在客户端组件中使用 FormattedRelativeTime 组件。
新建一个文件 app/components/RelativeTime.tsx。
// app/components/RelativeTime.tsx
'use client';
import { FormattedRelativeTime } from 'react-intl';
type Props = {
value: number;
unit: Intl.RelativeTimeFormatUnit;
};
export default function RelativeTime({ value, unit }: Props) {
return (
<FormattedRelativeTime
value={value}
unit={unit}
numeric="auto" // "auto" allows "yesterday" or "tomorrow"
style="long"
/>
);
}
2. 传递格式化选项
FormattedRelativeTime 组件支持多个关键属性:
value:单位数量。负值(如-2)表示过去(“2 天前”),正值(2)表示将来(“2 天后”)。unit:时间单位,如 'day'、'hour'、'minute' 或 'second'。numeric="auto":允许库使用“昨天”或“明天”这样的词语替代“1 天前”或“1 天后”。
3. 在页面中使用该组件
现在可以在任意页面中使用该组件。你需要在传递参数前自行计算时间差。
// app/[lang]/page.tsx
import RelativeTime from '@/app/components/RelativeTime';
export default function Home() {
// You would calculate these values dynamically
const daysSinceUpdate = -2;
const hoursUntilEvent = 3;
return (
<div>
<h1>Updates</h1>
<p>
File updated: <RelativeTime value={daysSinceUpdate} unit="day" />
</p>
<p>
Event starts: <RelativeTime value={hoursUntilEvent} unit="hour" />
</p>
</div>
);
}
访问 /en 的用户会看到 “文件已更新:2 天前” 和 “事件开始时间:3 小时后”。访问 /es 的用户会看到 “文件已更新:hace 2 días” 和 “事件开始时间:dentro de 3 horas”。