2016-09-30 15 views

回答

3

鉴于今年是4位和月和日都是2位,你可以使用此代码

var date1 = "20160923"; 
 

 
var formattedDate = date1.slice(0, 4) + "-" + date1.slice(4, 6) + "-" + date1.slice(6, 8); 
 

 
console.log(formattedDate);

-1

假设DATE1始终是一致的......

var date2 = date1.slice(0, 4) + '-' + date1.slice(4, 6) + '-' + date1.slice(6, 8); 
5

你可以使用正则表达式:

var ret = "20160923".replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3"); 
 
console.log(ret);

/)

2

有这个没有直接的方法,你可以写像使用原型对象InsertAt(char,pos)自己的方法【参考文献从here]

String.prototype.InsertAt=function(CharToInsert,Position){ 
    return this.slice(0,Position) + CharToInsert + this.slice(Position) 
} 

然后像这样使用它

"20160923".InsertAt('-',4); //Output :"2016-0923"