介绍
在前端开发工作中,经常会有根据特定格式格式化时间的需求,有时时间格式不一样,需要封装多个函数,导致有大量的相似功能的js函数,且扩展性比较低,故此封装FormatTime函数,提高扩展性,减少代码量。
使用
FormatTime(date,format)
date:Date类型、String类型
format:String类型
示例
调用>> FormatTime(new Date(),'YYYY-MM-DD hh:mm:ss')
输出>> 2024-10-08 22:18:18
调用>> FormatTime(new Date(),'YYYY年MM月DD日 hh:mm:ss')
输出>> 2024年10月08日 22:18:18
增加格式匹配列表
FormatTime 通过replace()链式调用,匹配formatTimeList中regExp(正则表达式)替换字符串,以达到格式化时间的效果。
数据结构: "模板字符串":{ regExp:[正则表达式], value:[替换后的内容] }
示例: "YYYY":{ regExp:/YYYY/g, value:date.getFullYear() },
注意: 在添加匹配项时应尽量避免写有包含关系的正则,以防匹配混乱。若必须使用包含关系的匹配项,可以将子集关系的置于后方。
如:
{
"#YYYY":{ regExp:/#YYYY/g, value:date.getFullYear() },
"YYYY":{ regExp:/YYYY/g, value:date.getFullYear() },
}
匹配列表
匹配字符串 | 输出结果 |
---|---|
YYYY | 2024 |
MM | 一位数补0如 08,两位数不做处理 |
DD | 同MM |
hh | 同MM |
mm | 同MM |
ss | 同MM |
代码
FormatTime(date,format) {
if(!date){
return null
}
if(typeof date === "string"){
date = new Date(date)
}
let formatTimeList = {
"YYYY":{
regExp:/YYYY/g,
value:date.getFullYear()
},
"MM":{
regExp:/MM/g,
value:String(date.getMonth() + 1).padStart(2,'0')
},
"DD":{
regExp:/DD/g,
value:String(date.getDate()).padStart(2,'0')
},
"hh":{
regExp:/hh/g,
value:String(date.getHours()).padStart(2,'0')
},
"mm":{
regExp:/mm/g,
value:String(date.getMinutes()).padStart(2,'0')
},
"ss":{
regExp:/ss/g,
value: String(date.getSeconds()).padStart(2,'0')
},
}
let result = format
Object.keys(formatTimeList).forEach(key=>{
result = result.replace(formatTimeList[key].regExp,formatTimeList[key].value)
})
return result
},