/**
* 获取日期或时间,自动补零
* @param {String} type 获取的日期或时间的类型,可选参数[year,month,day,hours,minutes,seconds]
*/
function getAnyDateOrTime(type){
let timestamp = Date.parse(new Date());
let date = new Date(timestamp);
let cbValue = 0
switch(type){
case 'year':
cbValue = date.getFullYear()
break;
case 'month':
cbValue = date.getMonth() + 1
break;
case 'day':
cbValue = date.getDate()
break;
case 'hours':
cbValue = date.getHours()
break;
case 'minutes':
cbValue = date.getMinutes()
break;
case 'seconds':
cbValue = date.getSeconds()
break;
}
if(type != 'year'){
// 将返回值转换为带有前导零的文本形式
return cbValue.toString().padStart(2, '0')
}else{
return cbValue
}
}
工作中用到的自己封装了一下,希望能帮到各位小伙伴~~~