一行原生js代码搞定日期的格式化
前言
之前在项目中格式化日期都是自己封装工具函数,或者使用moment时间库,但是因为项目中需要格式化时间的地方都比较简单,只需要格式化年月日,所以为了格式化年月日单独引入一个库,显然不太划算,最近在掘金看到一篇文章发现能通过原生的api获取日期对象并且格式化,所以就学习了一下,发现真的挺好用的,还不用担心浏览器兼容性问题,市面上主流的浏览器基本上都支持。
jsApi
new Intl.DateTimeFormat(locale,options).format(date),其中locale是语言对象,options是对时间格式化处理的参数,date是需要格式化的时间对象,可以不传,不传的话默认就是当前时间。
options参数具体有下面这些
- 日期格式dateStyle:
full、long、medium、short
new Intl.DateTimeFormat('zh',{dateStyle: 'full'}).format() // '2023年6月20日星期二'
new Intl.DateTimeFormat('zh',{dateStyle: 'short'}).format() // '2023/6/20'
new Intl.DateTimeFormat('zh',{dateStyle: 'long'}).format() // '2023年6月20日'
new Intl.DateTimeFormat('zh',{dateStyle: 'medium'}).format() //'2023年6月20日'
- 时间格式timeStyle:
full、long、medicum、short
new Intl.DateTimeFormat('zh',{timeStyle: 'full'}).format() // '中国标准时间 10:18:53'
new Intl.DateTimeFormat('zh',{timeStyle: 'short'}).format() //'10:19'
new Intl.DateTimeFormat('zh',{timeStyle: 'long'}).format() //'GMT+8 10:20:20'
new Intl.DateTimeFormat('zh',{timeStyle: 'medium'}).format() //'10:20:43'
3.时间段dayPeriod:narrow, short, long
new Intl.DateTimeFormat('zh',{dayPeriod: 'long'}).format() //上午
new Intl.DateTimeFormat('zh',{dayPeriod: 'short'}).format() //上午
new Intl.DateTimeFormat('zh',{dayPeriod: 'narrow'}).format() //上午
- 时间进制hour12:
true、false
new Intl.DateTimeFormat('zh',{hour12: false,timeStyle: 'short'}).format(new Date('2021-03-22 17:40')) //'17:40'
new Intl.DateTimeFormat('zh',{hour12: true,timeStyle: 'short'}).format(new Date('2021-03-22 17:40')) // '下午05:40'
- 获取周几weekday:
long、short、narrow
new Intl.DateTimeFormat('zh',{weekday: 'long'}).format() // 星期二
new Intl.DateTimeFormat('zh',{weekday: 'short'}).format() //周二
new Intl.DateTimeFormat('zh',{weekday: 'long'}).format() // 二
- 年月日时分秒:
year,month,day,hour,minute,second,参数:numeric、2-digit
new Intl.DateTimeFormat('zh',{year: 'numeric',month: 'numeric',day: 'numeric',hour: 'numeric',minute: 'numeric',second: 'numeric'}).format() // '2023/6/20 11:10:30'
new Intl.DateTimeFormat('zh',{year: '2-digit',month: '2-digit',day: '2-digit',hour: '2-digit',minute: '2-digit',second: '2-digit'}).format() //'23/06/20 11:12:00'
浙公网安备 33010602011771号