-1

this javascript calculate worng number of the days

i select two dates

1st date 2013-01-01 2nd date 2013-12-31

and it is showing worng answer 365 days

i was calculte manual it is worng correct answer is 364 days

how can i fix this issue please help me thanks

live demo

form

<input class='fromdate' />
<input class='todate' />
<input class='calculated' />
<input class='minim' /><br/><p><font size="3"><b>For more FAQs Visit<a  target="_blank"href="http://jqfaq.com/"</a> JQFaq.com</b></font></p>
<iframe id="iframe1" src="http://jqfaq.com/AdPage.html" style="width:100%; height:115px; border:none;"
/>

javascript

$('.fromdate').datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true,
});
$('.todate').datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true,
});
$('.fromdate').datepicker().bind("change", function () {
    var minValue = $(this).val();
    minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
    $('.todate').datepicker("option", "minDate", minValue);
    calculate();
});
$('.todate').datepicker().bind("change", function () {
    var maxValue = $(this).val();
    maxValue = $.datepicker.parseDate("yy-mm-dd", maxValue);
    $('.fromdate').datepicker("option", "maxDate", maxValue);
    calculate();
});

function calculate() {
    var d1 = $('.fromdate').datepicker('getDate');
    var d2 = $('.todate').datepicker('getDate');
    var diff = 1;
    if (d1 && d2) {
        diff = diff + Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
    }
    $('.calculated').val(diff);
    $('.minim').val(d1)
}
user3000993
  • 55
  • 1
  • 9

3 Answers3

1

Like this way you can do it -

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);

var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

Refer this

Suhas Gosavi
  • 2,170
  • 19
  • 40
0

Try this to calculate the "diff" in function calculate():

   if (d1 && d2) {
        var timeDiff = Math.abs(d2.getTime() - d1.getTime());
        diff = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
    }
Nidhin Bose J.
  • 1,092
  • 15
  • 28
0

In your code the var diff=1 is causing problem.

change it to var diff=1 then see you will get 364 days.

user234
  • 120
  • 1
  • 10