Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change date from YYYYMMDD to YYYY-MM-DD Javascript

I'm trying to convert a string from my database that is formatted as YYYYMMDD and is placed in the input box id="startingdate". How would I convert it to YYYY-MM-DD at the other input box id="startingdate1"?

<input type="" id="startingdate1" name="startingdate1" size="20" class="form-control col-md-7 col-xs-12" placeholder="YYYY-MM-DD"/>
<input id="startingdate" name="startingdate" type="hidden"/>
like image 872
Hafiz Idris Avatar asked Apr 15 '16 04:04

Hafiz Idris


3 Answers

s = s.replace(/(\d{4})(\d{2})(\d{2})/g, '$1-$2-$3');

This uses a regular expression to replace a sequence of four digits, followed by a sequence of two digits, followed by a sequence of two digits, with the first, plus a -, plus the second, plus a -, plus the third.

like image 61
Akhilesh Singh Avatar answered Sep 20 '22 20:09

Akhilesh Singh


Not using a regular expression if for some reason you don't want to:

var startDate = document.getElementById('startingdate').value;
var displayDate = document.getElementById('startingdate1');

var year = startDate.substring(0, 4);
var month = startDate.substring(4, 6);
var day = startDate.substring(6, 8);

displayDate.value = year + '-' + month + '-' + day;
<input type="" id="startingdate1" name="startingdate1" size="20" class="form-control col-md-7 col-xs-12" placeholder="YYYY-MM-DD"/>
<input id="startingdate" name="startingdate" type="hidden" value="20160415"/>
like image 45
damo-s Avatar answered Sep 23 '22 20:09

damo-s


The most reliable way for me so far was:

var a = "YYYYMMDD";
var b = [a.slice(0, 4), "-", a.slice(4, 6), "-", a.slice(6, 8)].join('');
console.log(b);
like image 41
wfaye Avatar answered Sep 23 '22 20:09

wfaye