---
title: "Intl 日期与相对时间:DateTimeFormat 与 RelativeTimeFormat"
keywords:
- Intl.DateTimeFormat
- Intl.RelativeTimeFormat
- 时区
- 本地化
- 格式化
description: "介绍日期时间与相对时间的本地化格式化,涵盖时区/日历选项与语义、显示粒度与多语言支持,提供示例与工程建议。"
categories:
- 文章资讯
- 编程技术
---
概述
Intl 提供本地化的日期时间与相对时间格式化能力,支持时区、日历与粒度选项。适用于国际化站点的时间呈现与人性化描述(如“3 分钟前”)。
示例
const dtf = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'Asia/Shanghai' })
console.log(dtf.format(new Date()))
const rtf = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'auto' })
console.log(rtf.format(-3, 'minute')) // 3 分钟前
工程建议
- 语言与区域:按用户偏好与内容语言选择 locale;处理时区显示与存储分离。
- 粒度与性能:缓存格式器实例;避免高频创建影响性能。
- 回退策略:不支持平台使用库回退;保持一致体验。
参考与验证
- MDN Intl.DateTimeFormat 文档:https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
- MDN Intl.RelativeTimeFormat 文档:https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat
- ECMA-402 规范:https://tc39.es/ecma402/

发表评论 取消回复