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"

参考资料

参数

名称类型描述
dateDate要格式化的日期对象
optionsDateTimeFormatOptions & { 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?stringIANA 时区标识
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.DateTimeFormat options
  • 指定时区时可正确处理
  • 不同的 locale 具有不同的日期/时间默认格式,以及对 12 小时制与 24 小时制的偏好

后续步骤

这份指南怎么样?

formatDateTime