1

I know this question has been asked before, but I could not find anything close to what I am trying to do. I am using jQuery Datepicker http://keith-wood.name/datepick.html and using the range with 2 calendars. In my app I have a service that I charge a 1 day price for. What I want to do is offer the end user a date range to pick how many days they would like to purchase and show them the total. To get me started, I just want to know how to calculate the amount of days selected in the range.

Here is my code:

<?php 
// this has the css and javascript includes
include('includes/header.php');
?>
<div class="container">
<div class="row">
<div class="span3"></div>
<div class="span9">
    <form>
  <div class="controls">
    <input id="range2Picker" name="range2Picker" value=""  class="input-large" required="" type="text"> 
  </div>
</form>
</div>
</div>

</div>

<script>
$('#range2Picker').datepick({ 
    date1 = new Date(date1);
    date2 = new Date(date2);
    rangeSelect: true, 
    monthsToShow: 2,
    changeMonth: false,
    minDate: +3,
    onClose: function(date1, date2) { 
        var timediff = date2 - date1;
        alert('Number of days are: ' + timediff); 
    } 

});

</script>
DSmith
  • 135
  • 1
  • 3
  • 12

2 Answers2

1

The answers involving Math.ceil fall prey to problems around Summer Time hours (Daylight Savings Time). For instance, in the US:

Math.ceil((new Date("November 4, 2013").getTime() - 
           new Date("November 2, 2013").getTime()) / (1000 * 3600 * 24)); //=> 3

Math.floor would have the same problem in the Spring:

Math.floor((new Date("March 11, 2013").getTime() - 
            new Date("March 9, 2013").getTime()) / (1000 * 3600 * 24)); // 1

Better would be Math.round:

var days = Math.round( (1*date2 - 1*date1) / 86400000, 0);
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
  • I suspect he also needs a minimum of 1 day, in case date1==date2 – Paul Aug 21 '13 at 01:19
  • @Paul: Possibly, although if that's the case, it probably needs a plus one. (So today - yesterday => 2.) I don't know the business case well enough, but it's easy enough to add if necessary. – Scott Sauyet Aug 21 '13 at 01:26
0

it gives you difference in millis, convert them into days

var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays)​;
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531