/*
* params: 任意参数分割日期,默认汉字格式
* return: 返回指定格式日期
*/
~ function() {
// 封装格式日期函数
function formatTime(format = 'cn') { //格式默认为中文
time = this.match(/\d+/g);//将日期拆分成数组
let template = format === 'cn' ? "{0}年{1}月{2}日 {3}时{4}分{5}秒" : `{0}${format}{1}${format}{2} {3}:{4}:{5}`;//判断日期模板
return template = template.replace(/\{(\d+)\}/g, (content, $1) => { //将模板中指定内容替换
let newtime = time[$1] || "00";// 自动将缺少的时间变为00
return newtime = newtime.length < 2 ? "0" + newtime : newtime;//将小于两位的时间前面加一个字符串0
});
};
String.prototype['formatTime'] = formatTime;//挂载到字符串原型
}();
//测试
let time1='2020年9月22号 12:22:33';
console.log(time1.formatTime());//'2020年09月22日 12时22分33秒'
let time2='2020年9月22号';
console.log(time2.formatTime());//'2020年09月22日 00时00分00秒'
let time3='2020年9月22号 12:22:33';
console.log(time3.formatTime('-'));//'2020-09-22 12:22:33'
let time4='2020年9月22号';
console.log(time4.formatTime('+'));//'2020+09+22 00:00:00'
let time5='2020-09-22 12:22:33';
console.log(time5.formatTime());//'2020年09月22日 12时22分33秒'
封装时间格式
最新推荐文章于 2024-07-31 16:33:32 发布