2016-09-30 57 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"