'How to calculate date difference between two text inputs?
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.
Solution 1:[1]
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>
`
Solution 2:[2]
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.
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pratik Kabade |
| Solution 2 | Farid Nouri Neshat |
