JS时间格式化方案汇总

288 阅读5分钟

目前JS实现时间格式化有很多种方案,但具体采用哪一种需要看项目需求以及对应的技术栈。下面汇总常见的方式:

Date 对象 API

Date 对象是 JavaScript 处理日期和时间的基本工具。它提供了一系列方法来获取和设置日期时间的各个部分,以及进行日期和时间的计算。

// *****************************************************
// 创建 date 对象
// *****************************************************
// 当前日期和时间
const currentDate = new Date();
// 根据毫秒数创建日期
const specificDate = new Date(1637078487000);
// 根据字符串创建日期
const dateString = '2022-11-16T12:34:45';
const dateFromString = new Date(dateString);
// *****************************************************
// 获取日期和时间部分
// *****************************************************
const year = currentDate.getFullYear();
const month = currentDate.getMonth(); // 0 到 11,需手动+1
const day = currentDate.getDate();
const hours = currentDate.getHours();
const minutes = currentDate.getMinutes();
const seconds = currentDate.getSeconds();
// *****************************************************
// 设置日期和时间部分
// *****************************************************
currentDate.setFullYear(2023);
currentDate.setMonth(5); // 0 到 11
currentDate.setDate(25);
currentDate.setHours(14);
currentDate.setMinutes(30);
currentDate.setSeconds(0);

date 对象实现时间格式化的方式有好几种:

手动格式化

这是一种基本的方式,但需要手动构建格式。

const date = new Date();
const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
console.log(formattedDate);

toLocaleString

Date 对象有一个 toLocaleString 方法,该方法可以格式化日期和时间,同时衍生出另外两种分别获得日期和时间的方法。

  • 字段说明:
    • 日期+时间: toLocaleString()
    • 日期: toLocaleDateString()
    • 时间: toLocaleTimeString()
  • 参数说明 (非必填)
    • 'en-US', { timeZone: 'America/New_York' }
    • en-US : 地区设置(String)
    • { timeZone: 'America/New_York' }: 日期时间格式和时区信息(Object)
const date = new Date();
const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' };
const formattedDate = date.toLocaleString('zh-CN', options);
console.log(formattedDate); // 2024/01/14 14:55:26

Intl.DateTimeFormat

Intl.DateTimeFormat 是 ECMAScript 国际化 API 的一部分,用于格式化日期和时间。它提供了一种灵活的方式来创建符合不同地区和语言习惯的日期时间字符串。

// *****************************************************
// 创建 Intl.DateTimeFormat 对象
// *****************************************************
// 'zh-CN' 是地区(Locale)字符串,表示中文简体。
// 如果不设置,将根据用户浏览器的语言设置来自动选择合适的格式,实现多语言支持
const dateFormatter = new Intl.DateTimeFormat('zh-CN');
// *****************************************************
// 格式化时间
// *****************************************************
// 使用 format 方法来格式化一个 Date 对象
const date = new Date();
const formattedDate = dateFormatter.format(date);
console.log(formattedDate); // 2024/1/14

格式化选项

Intl.DateTimeFormat 允许你通过第二个参数传递一些选项

const options = {
  weekday: 'long', // 'short', 'narrow'
  year: 'numeric', // '2-digit'
  month: 'long', // 'short', 'narrow'
  day: 'numeric', // '2-digit'
  hour: '2-digit', // 'numeric'
  minute: '2-digit', // 'numeric'
  second: '2-digit', // 'numeric'
  timeZoneName: 'short', // 'long'
};
const dateFormatterWithOptions = new Intl.DateTimeFormat('zh-CN', options);
const formattedDateWithOptions = dateFormatterWithOptions.format(date);
console.log(formattedDateWithOptions); // 2024年1月14日星期日 GMT+8 15:08:43
选项描述
year'numeric' , '2-digit'年份显示方式。例如, 'numeric' 表示使用完整的四位年份,而 '2-digit' 表示使用两位年份。
month'numeric' , '2-digit' , 'long' , 'short' , 'narrow'月份的显示方式。例如, 'numeric' 表示使用数字表示月份,而 'long' 表示使用完整的月份名称。
day'numeric' , '2-digit'日期的显示方式,类似于年份
hour'numeric' , '2-digit'小时的显示方式,可与 hour12 一起使用
minute'numeric' , '2-digit'分钟的显示方式
second'numeric' , '2-digit'秒的显示方式
weekday'long' , 'short' , 'narrow'星期几的显示方式
era'long' , 'short' , 'narrow'时代的显示方式,例如公元前后
timeZoneName'short' , 'long'显示时区名称的方式
hour12true, false是否使用 12 小时制。如果为 true,则使用 12 小时制(上午/下午),如果为 false,则使用 24 小时制
formatMatcher'basic' , 'best fit'用于选择最佳匹配方式,以便于处理地区特定的日期和时间表达
timeZoneString指定时区的字符串,例如 'UTC''Europe/London' 。如果省略此选项,则使用运行时环境的默认时区

获取支持的选项

可以使用 resolvedOptions 方法来获取实际使用的选项:

const optionsUsed = dateFormatter.resolvedOptions();
console.log(optionsUsed);

兼容性

第三方库

使用第三方库,如 moment.jsday.js,它们提供了丰富的功能和更简单的 API 来格式化日期。需要注意的是,moment.js 已经被官方声明为不再维护,推荐使用 day.js (API类似,可快速上手)或原生的 JavaScript 日期对象。

使用 day.js 的例子:

import dayjs from 'dayjs';

// 创建 dayjs 对象
const now = dayjs();
// 格式化日期
const formattedDate = now.format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate);
// 自定义格式化字符串
const customFormattedDate = now.format('YYYY/MM/DD HH:mm:ss');
console.log(customFormattedDate);

支持的解析占位符列表

输入例子描述
YY01两位数的年份
YYYY2001四位数的年份
M1-12月份,从 1 开始
MM01-12月份,两位数
MMMJan-Dec缩写的月份名称
MMMMJanuary-December完整的月份名称
D1-31月份里的一天
DD01-31月份里的一天,两位数
H0-23小时
HH00-23小时,两位数
h1-12小时, 12 小时制
hh01-12小时, 12 小时制, 两位数
m0-59分钟
mm00-59分钟,两位数
s0-59
ss00-59秒 两位数
S0-9毫秒,一位数
SS00-99毫秒,两位数
SSS000-999毫秒,三位数
Z-05:00UTC 的偏移量
ZZ-0500UTC 的偏移量,两位数
AAM PM上午 下午 大写
aam pm上午 下午 小写
Do1st... 31st带序数词的月份里的一天
X1410715640.579Unix 时间戳
x1410715640579Unix 时间戳