0

I have two different dates inputs with HTML5 calendar One of it start date and the second is end date I just need to compute the days when the user selects start date and end date using javascript and use if condition for example if these days great than 10 hide some elements

var date1 = new Date($('#start').val());
var date2 = new Date($('#end').val());
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays);
start
<br />
<input id="start" type="date" data-date-inline-picker="true" />
<br />
end
<br />
<input id="end" type="date" data-date-inline-picker="true" />
<br />
<div id="demo">the days here</div>
Kareem Sultan
  • 180
  • 10

2 Answers2

0

Here it is. I bind an event to #endDate.

LInk to check --> https://jsfiddle.net/nmitic/rvpb3dfg/

<input id="start" type="date" data-date-inline-picker="true" />
<input id="end" type="date" data-date-inline-picker="true" />

  function getDifFDate(startDate, endDate) {
  var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
  var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
  return diffDays;
}

$('#end').on('change', function() {
  var date1 = new Date($('#start').val());
  var date2 = new Date($('#end').val());    

    if(getDifFDate(date1, date2) > 10) {
        console.log('do something here');
      }
});

NOTE You should implement validations of some sort, the event should not be fired if only one input date is selected.

Nikola Mitic
  • 1,298
  • 3
  • 11
  • 23
  • @KareemSultan—no, it doesn't. `Math.ceil` should be `Math.round` to account for daylight saving differences. Always rounding up will mean that going over the boundary going out of daylight saving will add an extra day. The difference in whole days between two dates is given by `Math.round((date1 - date2)/8.64e7)`. – RobG Jan 04 '18 at 23:13
  • Good catch! He should implement that. And I will update my answer. – Nikola Mitic Jan 04 '18 at 23:14
0

Please find the below code, the days will be hidden if the difference is greater than 10 days, else it will be visible.

function showdiff()
{
var date1 = new Date(document.getElementById("start").value);
var date2 = new Date(document.getElementById("end").value);
var timeDiff = (date2 - date1) / (24 * 3600 * 1000);
document.getElementById('demo').innerHTML = timeDiff;
if(timeDiff > 10)
{
 document.getElementById('demo').style.display = 'none';
}
alert(timeDiff);

} 
start
<br />
<input id="start" type="date" data-date-inline-picker="true" />
<br />
end
<br />
<input id="end" type="date" data-date-inline-picker="true" />
<br />
<div id="demo">the days here</div>
<button onclick="showdiff()">Difference</button>
Karan
  • 695
  • 1
  • 6
  • 16