# generaltranslation: General Translation Core SDK: formatRelativeTime URL: https://generaltranslation.com/zh/docs/core/class/methods/formatting/format-relative-time.mdx --- title: formatRelativeTime description: formatRelativeTime 方法的 API 参考,用于格式化相对时间值 --- ## 概述 `formatRelativeTime` 方法会根据特定于区域设置的惯例,使用显式指定的单位格式化相对时间值。 ```typescript const gt = new GT(); const formatted = gt.formatRelativeTime(-1, 'day', { locales: 'en-US', numeric: 'auto' }); // 返回:"yesterday" ``` ## 参考文档 ### 参数 | 名称 | 类型 | 说明 | | ---------- | ----------------------------- | -------------------------------------------------------------------------- | | `value` | `number` | 相对时间值 (过去为负值,未来为正值) | | `unit` | `Intl.RelativeTimeFormatUnit` | 时间单位 (`'second'`、`'minute'`、`'hour'`、`'day'`、`'week'`、`'month'`、`'year'`) | | `options?` | `object` | 格式化配置 | ### 选项 | 名称 | 类型 | 说明 | | ---------------- | ------------------------------- | ------------------------------ | | `locales?` | `string \| string[]` | 用于格式化的区域设置;如果未指定,则回退到实例的渲染区域设置 | | `numeric?` | `'always' \| 'auto'` | 是否始终使用数字形式输出。默认为 `'auto'` | | `style?` | `'long' \| 'short' \| 'narrow'` | 输出的长度。默认为 `'long'` | | `localeMatcher?` | `'best fit' \| 'lookup'` | 要使用的区域设置匹配算法 | ### 返回值 `string` - 经书式设置的相对时间字符串。 *** ## 示例 ```typescript copy import { GT } from 'generaltranslation'; const gt = new GT(); // 过去时间 gt.formatRelativeTime(-2, 'hour', { locales: 'en-US' }); // 返回:"2 hours ago" // 未来时间 gt.formatRelativeTime(3, 'day', { locales: 'fr-FR' }); // 返回:"dans 3 jours" // 使用 numeric: 'auto'(默认值) gt.formatRelativeTime(-1, 'day', { locales: 'en-US' }); // 返回:"yesterday" ``` *** ## 注意事项 * 默认值为 `numeric: 'auto'` 和 `style: 'long'` * 内部使用 [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat) ## 下一步 * 参见 [`formatRelativeTimeFromDate`](/docs/core/class/methods/formatting/format-relative-time-from-date),了解如何根据 Date 自动选择时间单位 * 参见独立的 [`formatRelativeTime`](/docs/core/functions/formatting/format-relative-time) 函数,了解如何在无需 GT 实例的情况下使用