Reputation: 3018
I have simple form which consists checkin and checkout dates. I need to calculate the date difference according to the user input and display. My code looks like below.
<tr>
<td class="searchFormSpace">Check in</td>
<td width="10px"></td>
<td><input name="checkinText" type="text" class="date" id="fromDatePicker" type="text" value="Select date" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Select date';}"></td>
<td width="20px"></td>
<td class="searchFormSpace">Check out</td>
<td width="10px"></td>
<td><input name="checkoutText" type="text" class="date" id="toDatePicker" type="text" value="Select date" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Select date';} " onchange=""></td>
<td width="20px"></td>
<td>Nights</td>
<td width="10px"></td>
<td><input style="width: 30px" type="text" name="noOfNightsText" id="noOfNightsText" ></td>
How to do this?
This is what I tried :
function dateDiff() {
try {
var d2=document.getElementById("toDatePicker").value;
var d1=document.getElementById("fromDatePicker").value;
alert(d2);
var t2 = d2.value.getTime();
var t1 = d1.value.getTime();
alert(parseInt((t2-t1)/(24*3600*1000)));
}
catch(ex) {
alert(ex);
}
}
But It didn't work.
Upvotes: 0
Views: 3660
Reputation: 69
function dateDiff() {
var d2 = document.getElementById("aa").value;
var d1 = document.getElementById("bb").value;
var t2 = new Date(d2);
var t1 = new Date(d1);
alert((t1 - t2) / (24 * 3600 * 1000));
}
<p>Check in</p> <input type="date" name="date" id="aa">
<p>Check out</p> <input type="date" name="date" id="bb">
<button onclick="dateDiff()">here</button>
`
Upvotes: 1
Reputation: 1221
Assuming you have two Date objects(JavaScript Objects), you can just subtract them to get the difference in milliseconds.
You will need to check compatibility of formats between the output of the datepicker you are using and the JavaScript Date Class Constructor.
Please refer to the code below:
var date1 = new Date(document.getElementById("fromDatePicker").value);
var date2 = new Date(document.getElementById("toDatePicker").value);
var difference = date2 - date1;
var days = difference/(24*3600*1000);
Upvotes: 1
Reputation: 30430
I believe the problem that is happening in here that the value
property of the elements are strings. You have to first parse them and convert them to Date object: new Date(document.getElementById("toDatePicker").value);
function dateDiff() {
var d2=document.getElementById("toDatePicker").value;
var d1=document.getElementById("fromDatePicker").value;
var t2 = new Date(d2);
var t1 = new Date(d1);
alert((t2-t1) / (24*3600*1000));
// You should get the number of days in between in here.
}
Upvotes: 0