I need to display two input boxes when a form loads and populate one with the current date (I have this working already), the other with tomorrows date, my code is not working, could someone explain why, thanks in advance!
<input type="text" id="txtArrival">
<input type="text" id="txtDeparture">
var aDate, dDate, a, days;
//arrival
aDate = new Pikaday({
field: document.getElementById('txtArrival'),
defaultDate: new Date(),
format: 'D MMM YYYY',
setDefaultDate: true,
minDate: new Date(),
onSelect: function () {
console.log(aDate.getMoment().format('DD/MM/YY'));
var s_date = this.getDate();
var e_date = dDate.getDate();
// regardless set the end date to be forced to select a date from the start date
dDate.setMinDate(this.getDate());
// if the start date is now > end date then change the end date
if (s_date > e_date) {
dDate.setDate(s_date);
}
}
});
// departure
dDate = new Pikaday({
field: document.getElementById('txtDeparture'),
defaultDate: new Date() + 1,
setDefaultDate: true,
format: 'D MMM YYYY',
onSelect: function () {
console.log(dDate.getMoment().format('DD/MM/YY'));
}
});
I think the problem is in the way you set the date in the dDate
field. new Date() + 1
will not add a day to the date (it may add a millisecond, or add "1" to the date string).
What you want to do is construct a date from its date part:
var date = new Date(); // todays date
date.setDate(date.getDate() + 1);
Then set it:
defaultDate: date,
... etc, etc
The reason your code doesn't work is that dates in javascript are technically an integer behind the scenes. The integer represents milliseconds (since 1/1/1970). So new Date() + 1
just adds a millisecond into the current date, and doesn't add a whole day.
You could add a day by calculating the number of miliseconds in a day and adding this number. Something like this might work:
defaultDate: new Date(new Date().getTime() + (1000 * 60 * 60 * 24))
This works because getTime()
gets the milliseconds since 1/1/1970, then we add a day in milliseconds and create a new date from that integer.
EDIT
In your comment you say you want to add a day to dDate
on the line dDate.setDate(s_date)
. Does s_date
need to remain the same date? If not, you could add a day to s_date
using my first method. If you can't alter s_date
you will need to create a new date object and add that.
Something like below should work (s_date
will retain it's original value).
if (s_date > e_date) {
var newDate = new Date(s_date.getTime());
newDate.setDate(newDate.getDate() + 1);
dDate.setDate(newDate);
}