Utility FunctionsFormatting
formatDateTime
独立函数,用于按照 locale 习惯格式化日期和时间
概述
独立的 formatDateTime 函数无需 GT 实例即可按照特定 locale 的习惯格式化日期和时间。
它与 GT 类方法具备相同功能,但可单独使用。
import { formatDateTime } from 'generaltranslation';
const formatted = formatDateTime(new Date(), {
locales: 'de-DE',
dateStyle: 'medium',
timeStyle: 'short'
});
// 返回:“26.09.2025, 17:33”参考资料
参数
| 名称 | 类型 | 描述 |
|---|---|---|
date | Date | 要格式化的日期对象 |
options | DateTimeFormatOptions & { locales?: string | string[] } | 带可选 locales 的格式化配置 |
DateTimeFormatOptions
| 名称 | 类型 | 描述 |
|---|---|---|
locales? | string | string[] | 用于格式化的语言环境(默认使用系统语言环境) |
dateStyle? | 'full' | 'long' | 'medium' | 'short' | 整体日期格式样式 |
timeStyle? | 'full' | 'long' | 'medium' | 'short' | 整体时间格式样式 |
weekday? | 'long' | 'short' | 'narrow' | 星期显示方式 |
year? | 'numeric' | '2-digit' | 年份显示方式 |
month? | 'numeric' | '2-digit' | 'long' | 'short' | 'narrow' | 月份显示方式 |
day? | 'numeric' | '2-digit' | 日显示方式 |
hour? | 'numeric' | '2-digit' | 小时显示方式 |
minute? | 'numeric' | '2-digit' | 分钟显示方式 |
second? | 'numeric' | '2-digit' | 秒显示方式 |
timeZone? | string | IANA 时区标识符 |
hour12? | boolean | 是否使用 12 小时制 |
返回值
string - 按照 locale 约定格式化的日期和时间。
示例
基本用法
import { formatDateTime } from 'generaltranslation';
// 使用显式 locale 的基本格式化
console.log(formatDateTime(date, { locales: 'en-US' }));
// 输出:“3/14/2024”
// 德语格式化
console.log(formatDateTime(date, { locales: 'de-DE' }));
// 输出:“14.3.2024”
// 多个 locale 的回退
console.log(formatDateTime(date, {
locales: ['ja-JP', 'en-US']
}));
// 输出:“2024/3/14”(日文格式)日期与时间格式
const date = new Date('2024-03-14T14:30:45Z');
// 完整日期格式
console.log(formatDateTime(date, {
locales: 'en-US',
dateStyle: 'full'
}));
// 输出:"Thursday, March 14, 2024"
// 长日期 + 短时间
console.log(formatDateTime(date, {
locales: 'fr-FR',
dateStyle: 'long',
timeStyle: 'short'
}));
// 输出:"14 mars 2024 à 07:30"
// 不同 locale 下的短格式
const locales = ['en-US', 'de-DE', 'ja-JP'];
locales.forEach(locale => {
console.log(`${locale}: ${formatDateTime(date, {
locales: locale,
dateStyle: 'short',
timeStyle: 'short'
})}`);
});
// 输出:
// en-US: 3/14/24, 7:30 AM
// de-DE: 14.03.24, 07:30
// ja-JP: 2024/03/14 7:30时区处理
const date = new Date('2024-03-14T14:30:45Z');
// 按不同时区进行格式化
const timeZones = [
'America/New_York',
'Europe/London',
'Asia/Tokyo'
];
timeZones.forEach(timeZone => {
const formatted = formatDateTime(date, {
locales: 'en-US',
timeZone,
dateStyle: 'medium',
timeStyle: 'medium'
});
console.log(`${timeZone}:${formatted}`);
});
// 输出可能因夏令时而有所不同备注
locales参数为可选项,未提供时默认使用系统 locale- 使用与 GT class 方法相同的底层
Intl.DateTimeFormat - 为提高在重复的 locale/options 组合下的性能,结果会在内部进行缓存
- 支持所有标准的
Intl.DateTimeFormatoptions - 指定时区后可正确处理
- 不同的 locales 有各自的默认日期/时间格式以及 12 小时制与 24 小时制偏好
后续步骤
- 查看
Intl.DateTimeFormat文档 以了解更多 options - 参阅
formatNum以进行独立的数字格式化 - 参阅
formatMessage以进行独立的消息格式化 - 查看 GT class
formatDateTime以了解基于实例的用法 - 参阅
formatRelativeTime以进行相对时间格式化
本指南如何?