前言
前端开发中,经常会使用到时间的转化功能,比如:yyyy-mm-dd 或 yyyy-mm-dd hh:ss:mm,等的时间需求。
自我封装的时间组件,记录一下,有什么不妥的的地方多多提点意见,共同学习。
直接贴代码
// 调用时,第一个传时间,第二个传返回的格式下面是一种,还可以这样传参 yyyy-MM-dd hh:ss,或 yyyy-MM-dd hh:ss:mm
function formatDate(date,fmt='yyyy-MM-dd') {
if(date===null)return;
if(typeof(date) == 'string'||typeof(date) == 'number')date = new Date(date);
if(/(y+)/.test(fmt)){
fmt = fmt.replace(RegExp.$1,(date.getFullYear()+'').substr(4-RegExp.$1.length));
let o;
if(fmt.includes('h')||fmt.includes('m')||fmt.includes('s')){
o ={
'M+':date.getMonth() +1,
'd+':date.getDate(),
'h+':date.getHours(),
'm+':date.getMinutes(),
's+':date.getSeconds()
};
}else{
o ={
'M+':date.getMonth() +1,
'd+':date.getDate()
};
};
for(let k in o){
if(new RegExp(`(${
k})`).test(fmt)){
let str = o[k]+'';
fmt =fmt.replace(RegExp.$1,(RegExp.$1.length===1)?str:padLeftZero(str));
}
}
}
return fmt;
}
function padLeftZero(str) {
return ('00'+str).substr(str.length); };
获取当前月份1号的年月日
function getOneDay() {
const date = new Date();
const year = date.getFullYear();
let month = date.getMonth() + 1;
month = (month < 10 ? "0" + month : month);
return year.toString() + '-' + month.toString() + '-01'
}