时间格式转换

it2024-11-21  14

/**时间格式转换 * var oldTime = new Date("2012/12/25 20:11:11"); var curTime = oldTime.format("yyyy-MM-dd hh:mm:ss"); */ export const dateToString = (timeStr,fmt) => { if(!timeStr){ return; } let time; if(new Date(timeStr).toJSON()){ time = new Date(timeStr); }else{ //解决IE new Date() 时间格式兼容问题 //2020-09-02T06:10:09.000+0000转换为2020-09-02 14:10:09 let ieTimeOld = new Date(timeStr.replace(/-/g,'/').replace('T',' ').replace('.000+0000','')); let ieTime = new Date( ieTimeOld.setHours(ieTimeOld.getHours() + 8)) time = new Date(ieTime); } var o = { "M+" : time.getMonth()+1, //月份 "d+" : time.getDate(), //日 "h+" : time.getHours(), //小时 "m+" : time.getMinutes(), //分 "s+" : time.getSeconds(), //秒 "q+" : Math.floor((time.getMonth()+3)/3), //季度 "S" : time.getMilliseconds() //毫秒 }; if(/(y+)/.test(fmt)) { fmt=fmt.replace(RegExp.$1, (time.getFullYear()+"").substr(4 - RegExp.$1.length)); } for(var k in o) { if(new RegExp("("+ k +")").test(fmt)){ fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); } } return fmt; } //yyyy-MM-dd hh:mm:ss 转为date export const stringToDate = (dateString)=> { if (dateString) { var arr1 = dateString.split(" "); var sdate = arr1[0].split('-'); var date = ""; if(arr1.length == 2){ var sTime = arr1[1].split(':') date = new Date(sdate[0], sdate[1]-1, sdate[2],sTime[0],sTime[1],sTime[2]); }else{ date = new Date(sdate[0], sdate[1]-1, sdate[2]); } return date; } } //获取上一个月份 yyyy-MM export const preMonth = (time)=>{ let year = time.getFullYear(); let month = time.getMonth(); if(month == 0){ year = year -1; month = 12; } if(month <10){ month = "0"+month; } return year+"-"+month; }
最新回复(0)