// 格式化时间 formatStr='yyyy-mm-dd h:i:s'
formatTime: function (time, formatStr){
let d = null;
if (time instanceof Date) {
d = time;
} else {
d = new Date(parseInt(time));
}
return formatStr.replace(/[a-z]+/g, (res) => {
switch (res.toLowerCase()) {
case 'yyyy':
return d.getFullYear();
case 'yy':
return d.getFullYear().toString().substr(2, 2);
case 'mm':
return zeroize(getMonth(d));
case 'm':
return getMonth(d);
case 'dd':
return zeroize(d.getDate());
case 'd':
return d.getDate();
case 'h':
return zeroize(d.getHours());
case 'i':
return zeroize(d.getMinutes());
case 's':
return zeroize(d.getSeconds());
}
});
},
function zeroize (value) {
if (value.toString().length === 1) {
return '0' + value;
} else {
return value;
}
}
function getMonth (d) {
let month = d.getMonth();
if (month == 12) {
month = 1;
} else {
month += 1;
}
return month;
}
通过正则表达式格式化时间,可得到任意格式的时间
最新推荐文章于 2023-09-08 14:54:00 发布
该博客深入探讨了一个JavaScript时间格式化函数的实现,包括将日期和时间转换为指定格式的功能。函数处理了多种时间元素如年、月、日、小时、分钟和秒,并通过zeroize辅助函数确保位数不足时前导零填充。此外,getMonth函数用于处理月份的加一逻辑。这篇博客对于理解JavaScript日期处理和自定义格式化很有帮助。
摘要由CSDN通过智能技术生成