Utility FunctionsFormatting
formatDateTime
独立函数,用于按 locale 约定格式化日期和时间
概览
独立的 formatDateTime 函数可按指定 locale 的本地化规范格式化日期和时间,无需依赖 GT 实例。
它提供与 GT class 方法相同的功能,但可单独使用。
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[] | 用于格式化的 locale(默认为系统 locale) | 
| 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"
// 跨 locales 的短格式
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
- 指定时区时可正确处理
- 不同的 locale 具有不同的日期/时间默认格式,以及对 12 小时制与 24 小时制的偏好
后续步骤
- 查看 Intl.DateTimeFormat文档 以了解更多可用的 options
- 查看 formatNum获取独立的数字格式化
- 查看 formatMessage获取独立的消息格式化
- 查看 GT class 的 formatDateTime了解基于实例的用法
- 查看 formatRelativeTime了解相对时间格式化
这份指南怎么样?

