Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem finding the difference in days between two dates

I have been using a tidy little routine that I found here to calculate the difference in days between two dates in AS3. I am getting some strange results and I am wondering if any of you inter-codal-mega-lords can shed some light?

Why is Q1 of 2010 coming up one day short, when in all other cases the routine is performing fine?

Many thanks in advance to anyone who can help!

        function countDays( startDate:Date, endDate:Date ):int
        {
            var oneDay:int = 24*60*60*1000; // hours*minutes*seconds*milliseconds
            var diffDays:int = Math.abs((startDate.getTime() - endDate.getTime())/(oneDay));
            return diffDays;
        }

        countDays( new Date( 2010, 00, 01 ), new Date( 2011, 00, 01 ) );
        // returns 365, which is correct

        countDays( new Date( 2010, 00, 01 ), new Date( 2010, 03, 01 ) );
        // returns 89, which is 1 day short

        countDays( new Date( 2010, 03, 01 ), new Date( 2010, 06, 01 ) );
        // returns 91, which is correct

        countDays( new Date( 2010, 06, 01 ), new Date( 2010, 09, 01 ) );
        // returns 92, which is correct

        countDays( new Date( 2010, 09, 01 ), new Date( 2011, 00, 01 ) );
        // returns 92, which is correct
like image 284
James Avatar asked Jan 22 '23 22:01

James


2 Answers

Below should work:

    function countDays( startDate:Date, endDate:Date ):int 
    { 
        var oneDay:int = 24*60*60*1000; // hours*minutes*seconds*milliseconds 
        var diffDays:int = Math.round(Math.abs((startDate.getTime() - endDate.getTime())/(oneDay))); 
        return diffDays; 
    } 
like image 53
John Hartsock Avatar answered Jan 28 '23 09:01

John Hartsock


Daylight Savings, maybe? You lose an hour in the first quarter, so your function must be truncating the int instead of rounding.

like image 36
uhleeka Avatar answered Jan 28 '23 11:01

uhleeka