JavaScript 日期格式化组件:简化日期处理
以下是一个基于原生JavaScript的日期格式化组件,它可以将日期对象格式化为指定格式的字符串。
var dateFormat = function(date, format) {
var map = {
'M': date.getMonth() + 1, // 月份
'd': date.getDate(), // 日
'h': date.getHours(), // 小时
'm': date.getMinutes(), // 分钟
's': date.getSeconds(), // 秒
'q': Math.floor((date.getMonth() + 3) / 3), // 季度
'S': date.getMilliseconds() // 毫秒
};
format = format.replace(/([yMdhmsqS])+/g, function(all, t){
var v = map[t];
if(v !== undefined){
if(all.length > 1){
v = '0' + v;
v = v.substr(v.length - 2);
}
return v;
}
else if(t === 'y'){
return (date.getFullYear() + '').substr(4 - all.length);
}
return all;
});
return format;
};
使用方法
var date = new Date();
dateFormat(date, 'yyyy-MM-dd hh:mm:ss');
输出结果
'2021-09-03 15:30:20'
支持的格式化字符
- y: 年份(例如:2021)
- M: 月份(例如:09)
- d: 日(例如:03)
- h: 小时(例如:15)
- m: 分钟(例如:30)
- s: 秒(例如:20)
- q: 季度(例如:3)
- S: 毫秒(例如:123)
原文地址: https://www.cveoy.top/t/topic/mRhz 著作权归作者所有。请勿转载和采集!