Reputation: 3095
In HTML I have a date input:
<input type="date" id="checkInDate" value="<?php echo date('Y-m-d'); ?>" />
And I subscribe to the change event using jquery:
$('#checkInDate').on('change', function()
{
});
How do I get the chosen value of that input date, add one to that date and set another input (checkOutDate) to that value? Below is what I currently have:
$('#checkInDate').on('change', function()
{
var checkInDate = $(this).val();
console.log(checkInDate); // result is yyyy-mm-dd, ex: 2015-02-20
var split = checkInDate.split('-');
var tomorrow = new Date(split[0], split[1], split[2], 0,0,0,0);
console.log(tomorrow); // result is Wed Mar 18 2015 00:00:00 GMT-0600 (Mountain Daylight Time)
});
However this is incorrect as the month 02 is being treated as the third month as months are 0-based.
Upvotes: 2
Views: 7589
Reputation: 36703
You need to subtract 1
in the month as in JS
months start from 0
And use getDate()
and setDate()
functions
var tomorrow = new Date(split[0], split[1]-1, split[2], 0,0,0,0);
tomorrow.setDate(tomorrow.getDate()+1);
console.log(tomorrow);
Upvotes: 0
Reputation: 5050
Try this :
$('#checkInDate').on('change', function()
{
var checkInDate = $(this).val();
var split = checkInDate.split('-');
var tomorrow = new Date(split[0], split[1]-1, parseInt(split[2])+1, 0,0,0,0);
$('#checkOutDate')[0].valueAsDate = tomorrow;
});
See JS Fiddle : http://jsfiddle.net/61bkhok3/1/
Upvotes: 0
Reputation: 35670
You can simplify this using the valueAsDate attribute:
$('#checkInDate')[0].valueAsDate = new Date();
$('#checkInDate').change(function() {
var date= this.valueAsDate;
date.setDate(date.getDate() + 1);
$('#checkOutDate')[0].valueAsDate = date;
});
$('#checkInDate').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Check-in Date: <input type="date" id="checkInDate" > <br>
Check-out Date: <input type="date" id="checkOutDate" disabled>
Upvotes: 5
Reputation: 4168
As mentioned, months are 0-based, so you have to fix the month value, and you can set the day one in advance with some subtle changes to your new Date()
call.
Here's an example:
var checkInDate = "2015-02-13";
var split = checkInDate.split('-');
var tomorrow = new Date(parseInt(split[0]), parseInt(split[1] - 1), parseInt(split[2]) + 1, 0,0,0,0);
alert(tomorrow);
Upvotes: 1
Reputation: 1287
Javascript Date
object has a getDate()
method
var dateObj = new Date(split[0], split[1], split[2], 0,0,0,0);
var tomorrow = dateObj.getDate()+1;
console.log(tomorrow);
Upvotes: 0