JavaScript date object from <input type=date>
how can I create the date object without parsing the string "Y-m-d" into pieces, or is the only way?
While Date.parse will convert strings in y/m/d/ format to date objects, manual parsing is the only sensible way:
// s is format y-m-d
// Returns a date object for 00:00:00 local time
// on the specified date
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0], --b[1], b[2]);
}
ES5 specifies a form of ISO 8601 that should be supported by all browsers, however it is not supported consistently or by all browsers in use.
Use valueAsDate
:
valueAsDate
Returns:Date
Returns / Sets the value of the element, interpreted as a date, ornull
if conversion is not possible.
Demo:
<input type="date" id="d" value="2018-02-14">
<button onclick="console.log( document.getElementById('d').valueAsDate )">
change the date (or not) and click me
</button>