JavaScript中处理日期时间本地化与格式化是前端开发中常见的需求,不同国家地区的日期展示顺序、时间格式、月份名称都存在差异,需要采用合适的技术方案实现适配。

原生日期基础
JavaScript内置的Date对象是处理日期时间的基础,通过它可以创建日期实例,获取对应的时间戳和基础的日期分量。
// 创建当前时间的Date实例 const now = new Date(); // 获取时间戳 const timestamp = now.getTime(); // 获取基础的日期分量 const year = now.getFullYear(); const month = now.getMonth() + 1; // 月份从0开始计数 const day = now.getDate(); const hours = now.getHours(); const minutes = now.getMinutes(); const seconds = now.getSeconds();
基础格式化方法
Date对象提供了几个基础的格式化方法,但是这些方法大多依赖运行环境,本地化支持有限。
toLocaleString系列方法
这类方法可以传入区域参数,实现简单的本地化适配,是早期常用的格式化方式。
const date = new Date('2024-05-20T14:30:00');
// 默认使用运行环境的区域设置
console.log(date.toLocaleString()); // 输出类似 2024/5/20 14:30:00
// 指定区域为美国
console.log(date.toLocaleString('en-US')); // 输出 5/20/2024, 2:30:00 PM
// 指定区域为日本
console.log(date.toLocaleString('ja-JP')); // 输出 2024/5/20 14:30:00
// 仅格式化日期部分
console.log(date.toLocaleDateString('zh-CN')); // 输出 2024/5/20
// 仅格式化时间部分
console.log(date.toLocaleTimeString('zh-CN')); // 输出 14:30:00
Intl.DateTimeFormat API
Intl.DateTimeFormat是ES2015引入的国际化API,专门用于日期时间的本地化格式化,功能比toLocaleString更强大,支持自定义更多格式选项。
基本使用
创建Intl.DateTimeFormat实例时,可以传入区域标识和格式选项,通过format方法生成格式化后的字符串。
const date = new Date('2024-05-20T14:30:00');
// 创建针对中文区域的格式化实例,指定日期和时间的展示样式
const formatter = new Intl.DateTimeFormat('zh-CN', {
dateStyle: 'full',
timeStyle: 'long'
});
console.log(formatter.format(date)); // 输出 2024年5月20日星期一 14:30:00
常用配置选项
除了预设的dateStyle和timeStyle,还可以单独配置各个日期分量的展示规则,满足自定义需求。
| 选项名称 | 可选值 | 说明 |
|---|---|---|
| year | numeric, 2-digit | 年份展示方式,numeric为完整年份,2-digit为两位年份 |
| month | numeric, 2-digit, long, short, narrow | 月份展示方式,long为完整月份名,short为缩写,narrow为最简形式 |
| day | numeric, 2-digit | 日期展示方式 |
| hour | numeric, 2-digit | 小时展示方式 |
| minute | numeric, 2-digit | 分钟展示方式 |
| second | numeric, 2-digit | 秒数展示方式 |
| hour12 | true, false | 是否使用12小时制,true为12小时制,false为24小时制 |
下面是一个自定义配置的示例:
const date = new Date('2024-05-20T14:30:00');
const customFormatter = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
console.log(customFormatter.format(date)); // 输出 2024年5月20日 14:30:00
第三方库方案
如果项目需要支持更多自定义格式,或者需要处理旧版浏览器的兼容问题,也可以考虑使用第三方日期处理库。
- date-fns:模块化设计,按需引入,支持本地化配置,体积小
- dayjs:API设计和moment.js类似,体积非常小,支持插件扩展本地化功能
以dayjs为例,使用本地化插件实现格式化的示例:
// 引入dayjs和本地化插件
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import localizedFormat from 'dayjs/plugin/localizedFormat';
// 注册插件
dayjs.extend(localizedFormat);
// 设置区域为中文
dayjs.locale('zh-cn');
const date = dayjs('2024-05-20T14:30:00');
// 使用本地化格式
console.log(date.format('LLLL')); // 输出 2024年5月20日星期一 14:30
场景选择建议
如果只需要基础的本地化适配,优先使用原生的Intl.DateTimeFormatAPI,不需要额外引入依赖,兼容性在现代浏览器中表现良好。如果需要复杂的自定义格式或者需要兼容非常旧的浏览器环境,可以选择合适的第三方库。在处理日期时间本地化时,需要注意避免手动拼接日期字符串,因为手动拼接无法适配不同区域的展示规则,容易出现格式错误的问题。
JavaScript日期时间格式化本地化Intl_DateTimeFormattoLocaleString修改时间:2026-06-16 16:06:35