I've an HTML5 datepicker, which value I want to change on button click.
<input type="date" id="datepicker" />
<button onclick="nextDay()">next</button>
My approach since the value is a string, is to parse it to Date, and after operating, convert it back to string. But my problem is, the Date's month, is from 0 to 11, whilst the datepicker's months are from 1 to 12.
The code:
// get the value
function getDatepicker() {
// get
var string = datepicker.val();
var date;
// verify the string is a valid date
if (isNaN(Date.parse(string))) {
// invalid date, get today()
date = new Date();
} else {
// String to Date
date = new Date(string);
}
return date;
}
// operate
function addDays(date, days) {
date.setDate( new Date(date.getDate() + days));
return date;
}
// set the value
function setDatepicker(date) {
function addZero(num) {
return ('0' + num).slice(-2);
}
date.setMonth( date.getMonth() +1 );
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var string = [year, addZero(month), addZero(day)].join('-');
datepicker.val(string);
}
var date = getDatepicker();
addDays(date,-1);
setDatepicker(date);
Apparently since the datepicker initial value is right, when converting to Date, it does it correctly, but when converting the Date to datepicker value it substracts one month. It works fine from day to day, but fails when changing the month, for example:
start date = 1/4/2017 -1day = 31/3/2017 +1month = 1/5/2017
And then the next time I get the datepicker value, will be 1/5/2017 -1month, and I'll be in an infinite loop.
Can someone please shed some light on how to fix that? Thanks in advance!
PS: tl;dr in bold :)