1,将"20180604231436"转换为2018-06-04 23:14:36,支持8位、10位、12位、14位的转换:
let occurTime = "20180604231436"; //原字符串
console.log(dateFormat(occurTime)); //调用方式
function dateFormat(date){
let newOccurTime;
if(date.length==14){
newOccurTime=insertStr(insertStr(insertStr(insertStr(insertStr(date,4,"-"),7,"-"),10," "),13,":"),16,":");
}else if(date.length==12){
newOccurTime=insertStr(insertStr(insertStr(insertStr(date,4,"-"),7,"-"),10," "),13,":");
}else if(date.length==10){
newOccurTime=insertStr(insertStr(insertStr(date,4,"-"),7,"-"),10," ");
}else if(date.length==8){
newOccurTime=insertStr(insertStr(date,4,"-"),7,"-");
}
function insertStr(soure, start, newStr){
return soure.slice(0, start) + newStr + soure.slice(start);
}
return newOccurTime;
}