@日期格式化方法
日期格式化
每次项目创建的时候都会重写一个日期方法,留下最近的日期方法
定义方法
function getFormatTime(time, format = 'YYYY-MM-DD hh:mm:ss') {
if(!time) return '';
var datetime = new Date(time);
var o = {
'Y+': datetime.getFullYear(), //年
"M+": datetime.getMonth() + 1, //月
"D+": datetime.getDate(), //日
"h+": datetime.getHours(), //小时
"m+": datetime.getMinutes(), //分
"s+": datetime.getSeconds(), //秒
"q+": Math.floor((datetime.getMonth() + 3) / 3), //季度
"S": datetime.getMilliseconds() //毫秒
};
if (/(Y+)/.test(format)) format = format.replace(RegExp.$1, (datetime.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
return format;
},
调用方式
getFormatTime(new Date()) // 2021-06-28 20:29:49
getFormatTime(new Date(), 'YYYY年MM月DD日') // 2021年06月28日
getFormatTime(new Date(), 'YYYY年M月D日') // 2021年6月28日
getFormatTime(new Date(), 'YYYY/M/D') // 2021年6月28日