new Intl.DateTimeFormat日期格式化
可以针对不同日期格式进行转换
比如:2024/03/16 2024-03-16 2024年03月16日等格式
//1.在main.js文件中引入全局方法
import global from "./utils/global"
//2.组件中使用
created() {
let nowTime = new Date();
let res = this.$global.dateFormatter(nowTime, 'yyyy年MM月dd日HH时mm分ss秒');
console.log('res', res); //2024年03月16日10时14分53秒
},
//3.全局封装一个日期格式化方法
const global = {
/*
zh-CN 中文
en-US 英式英语
en-CA 美式英语
*/
timeFormat (now) {
return new Intl.DateTimeFormat('zh-CN', { dateStyle: 'long' }).format(now);//2024年3月16日
//return new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium' }).format(now);//2024年3月16日
//return new Intl.DateTimeFormat('zh-CN', { dateStyle: 'short' }).format(now);//2024/3/16
//return new Intl.DateTimeFormat('en-US', { dateStyle: 'long' }).format(now);//March 16, 2024
//return new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' }).format(now);// Mar 16, 2024
//return new Intl.DateTimeFormat('en-US', { dateStyle: 'short' }).format(now);// 3/16/24
//return new Intl.DateTimeFormat('en-CA', { dateStyle: 'long' }).format(now);//March 16, 2024
//return new Intl.DateTimeFormat('en-CA', { dateStyle: 'medium' }).format(now);//March 16, 2024
//return new Intl.DateTimeFormat('en-CA', { dateStyle: 'short' }).format(now); //2024-03-16
},
// 创建 Intl.DateTimeFormat 对象并设置格式选项
/*
@times 日期 new Date()
@type 日期格式 yyyy/MM/dd;yyyy-MM-dd;yyyy年MM月dd日
@dateFormatter 使用this.$global.dateFormatter(times,type)
*/
dateFormatter (times, type) {
//https://tc39.es/ecma402/#sec-intl.datetimeformat.prototype.formatRange
const options = new Intl.DateTimeFormat('en-US', {
//weekday: 'long',//周几 可以是"narrow", "short", "long",
//era: 'short',//"narrow", "short", "long"
year: 'numeric', // 年份,可以是 "numeric"、"2-digit"
month: '2-digit', // 月份,可以是 "2-digit", "numeric", "narrow", "short", "long"
day: '2-digit', // 日期,可以是 "2-digit", "numeric"
//dayPeriod: 'long',// "narrow", "short", "long"
hour: 'numeric', // 小时,可以是 "2-digit", "numeric"
minute: 'numeric', // 分钟,可以是 "2-digit", "numeric"
second: 'numeric', // 秒,可以是 "2-digit", "numeric"
hour12: false, // 是否使用 24 小时制
});
let formattedDate = options.format(times);
if (type) {
const parts = formattedDate.split(/[/,\s:]/);//把字符串切割成数组['03', '16', '2024', '', '09', '56', '17']
//把日期转换成中国的顺序展示
const formattedString = type.replace(/(yyyy|MM|dd|HH|mm|ss)/g, (type) => {
switch (type) {
case 'yyyy': return parts[2]; //年
case 'MM': return parts[0]; //月
case 'dd': return parts[1]; //日
case 'HH': return parts[4]; //时
case 'mm': return parts[5]; //分
case 'ss': return parts[6]; //秒
default: return type;
}
});
return formattedString;
}
return formattedDate
}
}
export default global