3

I have this date1, I want to insert "-" to make it 2016-09-23. Is anyone know how to do this using javascript?

var date1 = "20160923";
AyDee
  • 201
  • 1
  • 5
  • 13

4 Answers4

13

You can use regex:

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

/)

velen
  • 164
  • 1
  • 4
12

Given that the year is 4 digit and month and day are 2 digit you can use this code

var date1 = "20160923";

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

console.log(formattedDate);
Weedoze
  • 13,683
  • 1
  • 33
  • 63
5

There is no direct method for this, you can write your own Method like InsertAt(char,pos) using Prototype object [References from here]

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

Then use it like this

"20160923".InsertAt('-',4); //Output :"2016-0923"
Community
  • 1
  • 1
Jaydip Jadhav
  • 12,179
  • 6
  • 24
  • 40
0

Assuming date1 is always consistent...

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