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"/>
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.
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"/>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With