javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JavaScript时间格式化API

全面解析JavaScript中时间格式化API实战指南

作者:excel

时间与日期,是前端开发中最容易“踩坑”的部分,本文将系统解析 JavaScript 提供的时间格式化方法,帮你彻底搞懂它们的差异、用途与正确使用方式

时间与日期,是前端开发中最容易“踩坑”的部分。不同浏览器、不同区域、甚至不同系统语言,都会造成输出不一致。本文将系统解析 JavaScript 提供的时间格式化方法,帮你彻底搞懂它们的差异、用途与正确使用方式。

一、背景:为什么会有这么多时间格式化方法

JavaScript 的时间系统基于 ECMAScript 时间标准,时间点以 UTC 为基准(Unix Epoch:1970-01-01 00:00:00 UTC)。
但由于前端代码运行在不同地域的用户设备中,所以:

二、核心 API 总览表

方法时区是否本地化是否可定制输出示例主要用途
toString()本地时间"Tue Nov 11 2025 17:00:00 GMT+0800 (China Standard Time)"调试/默认输出
toUTCString()UTC"Tue, 11 Nov 2025 09:00:00 GMT"标准化输出(日志/HTTP)
toGMTString()UTC"Tue, 11 Nov 2025 09:00:00 GMT"历史遗留(不推荐)
toISOString()UTC"2025-11-11T09:00:00.000Z"数据交换(JSON/HTTP)
toLocaleString()本地时区✅ 是✅ 是"2025/11/11 17:00:00"用户界面显示
Intl.DateTimeFormat任意指定✅ 是✅ 是"11 November 2025, 17:00:00"完全可控本地化输出

三、逐个详解与代码示例

toUTCString()

用途:输出 UTC 时间的 RFC1123 标准格式

语法

date.toUTCString();

示例:

const d = new Date('2025-11-11T09:00:00Z');
console.log(d.toUTCString());
// "Tue, 11 Nov 2025 09:00:00 GMT"

特性:

适用场景:

// 设置 HTTP 响应头
response.setHeader('Expires', new Date(Date.now() + 3600000).toUTCString());

toGMTString()(已废弃)

用途toUTCString() 的旧版本,早期 Netscape/IE 兼容接口。

语法:

date.toGMTString();

说明:

toLocaleString()

用途:输出与用户地区语言相符的本地化时间字符串。

语法:

date.toLocaleString([locales], [options]);

参数说明:

参数类型说明
localesstring 或 string[]语言代码(如 'zh-CN', 'en-US')
optionsobject格式化选项

常用选项:

{
  timeZone: 'Asia/Shanghai', // 指定时区
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false
}

示例:

const d = new Date('2025-11-11T09:00:00Z');
console.log(d.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }));
// "2025/11/11 17:00:00"

console.log(d.toLocaleString('en-US', { timeZone: 'America/New_York' }));
// "11/11/2025, 4:00:00 AM"

可本地化、可控、最灵活。

toISOString()

用途:输出 ISO 8601 标准的 UTC 时间字符串。

语法:

date.toISOString();

输出示例:

new Date('2025-11-11T09:00:00Z').toISOString();
// "2025-11-11T09:00:00.000Z"

特性:

示例:

JSON.stringify({ createdAt: new Date().toISOString() });

Intl.DateTimeFormat

用途:提供强大的国际化时间格式化能力。

语法:

new Intl.DateTimeFormat(locales, options).format(date);

示例:

const d = new Date('2025-11-11T09:00:00Z');
const fmt = new Intl.DateTimeFormat('en-GB', {
  timeZone: 'UTC',
  dateStyle: 'full',
  timeStyle: 'long'
});
console.log(fmt.format(d));
// "Tuesday, 11 November 2025 at 09:00:00 GMT"

更细粒度控制:

const custom = new Intl.DateTimeFormat('zh-CN', {
  timeZone: 'Asia/Shanghai',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long',
  hour: '2-digit',
  minute: '2-digit'
});
console.log(custom.format(d));
// "2025年11月11日星期二 17:00"

支持:

四、对比实测:同一个时间,不同输出

const d = new Date('2025-11-11T09:00:00Z');

console.log(d.toString());         // "Tue Nov 11 2025 17:00:00 GMT+0800 (China Standard Time)"
console.log(d.toUTCString());      // "Tue, 11 Nov 2025 09:00:00 GMT"
console.log(d.toISOString());      // "2025-11-11T09:00:00.000Z"
console.log(d.toLocaleString());   // "2025/11/11 17:00:00"
console.log(
  new Intl.DateTimeFormat('en-US', { timeZone: 'UTC' }).format(d)
);                                 // "11/11/2025"

总结图示:

方法时区输出可定制推荐用途
toUTCString()UTC机器可读、HTTP Header
toGMTString()UTC已废弃
toLocaleString()本地时区用户界面展示
toISOString()UTC数据序列化、存储
Intl.DateTimeFormat任意✅✅✅最强国际化控制

五、潜在问题与实战建议

问题说明建议
不同浏览器格式差异特别是 toLocaleString()显式指定 locale + timeZone
服务器和客户端时区不一致SSR 输出 UTC、CSR 输出本地统一 timeZone(如 'UTC' 或 'Asia/Shanghai')
想统一格式输出toUTCString() 太固定改用 Intl.DateTimeFormat 或 dayjs
移动端差异ICU 版本不同避免依赖系统默认格式

六、实践案例:统一格式化函数封装

function formatDate(date, opts = {}) {
  const {
    locale = 'zh-CN',
    timeZone = 'Asia/Shanghai',
    options = {}
  } = opts;

  const fmt = new Intl.DateTimeFormat(locale, {
    timeZone,
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
    ...options
  });
  return fmt.format(date);
}

console.log(formatDate(new Date(), { timeZone: 'UTC' }));
// 输出如:2025/11/11 09:00:00

七、结语:选择建议总结

场景推荐 API
机器通信 / JSON / HTTPtoISOString() / toUTCString()
用户界面显示(国际化)toLocaleString() 或 Intl.DateTimeFormat
跨区域一致性(前后端)固定使用 UTC + 格式化控制
需要灵活格式使用 Intl.DateTimeFormat 或 dayjs

一句话总结:

到此这篇关于全面解析JavaScript中时间格式化API实战指南的文章就介绍到这了,更多相关JavaScript时间格式化API内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文