日复一日,必有精进|

晨米酱

园龄:4年3个月粉丝:5关注:1

JS时间格式化方案汇总

目前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',
    • 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' 显示时区名称的方式
hour12 true, false 是否使用 12 小时制。如果为 true,则使用 12 小时制(上午/下午),如果为 false,则使用 24 小时制
formatMatcher 'basic' , 'best fit' 用于选择最佳匹配方式,以便于处理地区特定的日期和时间表达
timeZone String 指定时区的字符串,例如 '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);

支持的解析占位符列表

输入 例子 描述
YY 01 两位数的年份
YYYY 2001 四位数的年份
M 1-12 月份,从 1 开始
MM 01-12 月份,两位数
MMM Jan-Dec 缩写的月份名称
MMMM January-December 完整的月份名称
D 1-31 月份里的一天
DD 01-31 月份里的一天,两位数
H 0-23 小时
HH 00-23 小时,两位数
h 1-12 小时, 12 小时制
hh 01-12 小时, 12 小时制, 两位数
m 0-59 分钟
mm 00-59 分钟,两位数
s 0-59
ss 00-59 秒 两位数
S 0-9 毫秒,一位数
SS 00-99 毫秒,两位数
SSS 000-999 毫秒,三位数
Z -05:00 UTC 的偏移量
ZZ -0500 UTC 的偏移量,两位数
A AM PM 上午 下午 大写
a am pm 上午 下午 小写
Do 1st... 31st 带序数词的月份里的一天
X 1410715640.579 Unix 时间戳
x 1410715640579 Unix 时间戳

本文作者:晨米酱的博客

本文链接:https://www.cnblogs.com/chenmijiang/p/17963814

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   晨米酱  阅读(480)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起