格式化时间的函数
这个系列放一些经常会用到的函数,记录自己平时用到的函数,下次需要时方便使用
设置任何格式的时间函数
/**
* 格式化时间函数
* @param time 时间戳
* @param format 所需返回的时间格式
*/
function formatDate(time,format='YY-MM-DD hh:mm:ss'){
const date = new Date(time);
const year = date.getFullYear(),
month = date.getMonth()+1,//月份是从0开始的
day = date.getDate(),
hour = date.getHours(),
min = date.getMinutes(),
sec = date.getSeconds();
const preArr = Array.apply(null,Array(10)).map(function(elem, index) {
return '0'+index;
});
return format.replace(/YY/g, year)
.replace(/MM/g, preArr[month] || month)
.replace(/DD/g, preArr[day] || day)
.replace(/hh/g, preArr[hour] || hour)
.replace(/mm/g, preArr[min] || min)
.replace(/ss/g, preArr[sec] || sec);
}
formatDate(new Date().getTime());//2022-04-18:05:44
formatDate(new Date().getTime(),'YY年MM月DD日');//2022年05月12日
formatDate(new Date().getTime(),'今天是YY/MM/DD hh:mm:ss');//今天是2022/04/18 10:07:45