首页 > 其他分享 >JS时间格式化方案汇总

JS时间格式化方案汇总

时间:2024-01-14 16:13:00浏览次数:21  
标签:digit const 汇总 numeric JS currentDate 日期 date 格式化

目前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 时间戳

标签:digit,const,汇总,numeric,JS,currentDate,日期,date,格式化
From: https://www.cnblogs.com/chenmijiang/p/17963814

相关文章

  • js delete()和 clear()函数
    constm=newMap();constfunctionKey=function(){};constsymbolKey=Symbol();constobjectKey=newObject();m.set(functionKey,"functionValue");m.set(symbolKey,"symbolValue");m.set(objectKey,"ob......
  • js Map 基本API
    使用new关键字和Map构造函数可以创建一个空映射:constm=newMap();如果想在创建的同时初始化实例,可以给Map构造函数传入一个可迭代对象,需要包含键/值对数组。可迭代对象中的每个键/值对都会按照迭代顺序插入到新映射实例中://使用嵌套数组初始化映射constm1=newM......
  • js Map函数
    定型数组中值的下溢和上溢不会影响到其他索引,但仍然需要考虑数组的元素应该是什么类型。定型数组对于可以存储的每个索引只接受一个相关位,而不考虑它们对实际数值的影响。以下代码演示了如何处理下溢和上溢://长度为2的有符号整数数组//每个索引保存一个二补数形式的有符号......
  • js 合并、复制和修改定型数组
    定型数组同样使用数组缓冲来存储数据,而数组缓冲无法调整大小。因此,下列方法不适用于定型数组:concat()pop()push()shift()splice()unshift()不过,定型数组也提供了两个新方法,可以快速向外或向内复制数据:set()和subarray()。set()从提供的数组或定型数组中把值复制到当前定型数组......
  • js 定型数组行为
    //创建一个长度为6的Int32Arrayconstints2=newInt32Array(6);//每个数值使用4字节,因此ArrayBuffer是24字节alert(ints2.length);//6//类似DataView,定型数组也有一个指向关联缓冲的引用alert(ints2.buffer.byteLength);//24//创建一个包含[2,4,6,8]的Int......
  • js边界情形
    //在内存中分配两个字节并声明一个DataViewconstbuf=newArrayBuffer(2);constview=newDataView(buf);//填充缓冲,让第一位和最后一位都是1view.setUint8(0,0x80);//设置最左边的位等于1view.setUint8(1,0x01);//设置最右边的位等于1//缓冲内容(为方便阅读,人......
  • Json Schema介绍 和 .net 下的实践 - 基于Lateapexearlyspeed.Json.Schema - 基础1 -
    本系列旨在介绍JsonSchema的常见用法,以及.net实现库Lateapexearlyspeed.Json.Schema的使用这篇文章将介绍JsonSchema中的type关键字,和string类型的常见验证功能。用例基于.net的LateApexEarlySpeed.Json.Schemanugetpackage。这是新创建的一个JsonSchema在.net下的高性能......
  • C#调用webapi发送带json参数的post请求
    嗯。。很久不更新,因为跳槽新公司了,要学的东西太多太忙了。也没时间记录,今天又写了一个C#调用webapi发送带json参数的post请求拿数据的方法,所以来到这里记录一下///<paramname="url">请求地址</param>///<paramname="jsonParas">请求体</param>///<paramnam......
  • C#将从数据库查处的table格式的数据转为json
    这里的代码是封装好的类,将Datatable作为参数传进来即可解析出json格式的数据,看代码publicstaticstringToJson(DataTabledt){intcount=dt.Rows.Count;//将DataTable格式的数据转换成json格式StringBuilderjsonBuilder=ne......
  • SpringBoot集成Jackson实现JSON序列化
    一、前言Jackson是一个在Java中常用的JSON序列化和反序列化库,它具有操作简单、性能优秀、支持多种数据格式等特点,被广泛应用于各种服务端开发中。SpringMVC框架的默认json解析器也是Jackson。当前常见的json解析器还有Gson、fastjson等,jackson的优势是解析大的json文件处理速度快,运......