Calculating number of days between two dates that are in a leap year

ScottR picture ScottR · Jul 17, 2009 · Viewed 10.7k times · Source

Given two dates, what is the best method to calculate the number of days between those two dates that fall in a leap year.

For example if d1 = 12/1/2007 and d2 = 1/31/2008 then the total number of days between d1 and d2 would be 62 and the number of days that fall in a leap year would be 31.

Another example is if d1 = 12/1/2007 and d2 = 6/30/2012 then the total number of days between d1 and d2 would be 1674 and the number of days that fall in a leap year would be 548.

I already have function to calculate if a specific year is a leap year and and a function to calculate the number of days between two dates.

If anyone has such a algorithm in Delphi (Pascal) or C/C++/C# that would be greatly appreciated. Any suggestions and assistance would be great.

Answer

kiran raj picture kiran raj · May 16, 2013

The solution is in python, and it shouldn't be hard to convert to any other language.

def isLeapYear(year):
    if year%4 == 0:
        if year%100 == 0:
            if year%400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    cumDays = [0,31,59,90,120,151,181,212,243,273,304,334] #cumulative Days by month
    leapcumDays = [0,31,60,91,121,152,182,213,244,274,305,335] # Cumulative Days by month for leap year
    totdays = 0
    if year1 == year2:
        if isLeapYear(year1):
            return (leapcumDays[month2-1] + day2) - (leapcumDays[month1-1] + day1)
        else:
            return (cumDays[month2-1] + day2) - (cumDays[month1-1] + day1)

    if isLeapYear(year1):
        totdays = totdays + 366 - (leapcumDays[month1-1] + day1)
    else:
        totdays = totdays + 365 - (cumDays[month1-1] + day1)

    year = year1 + 1
    while year < year2:
        if isLeapYear(year):
            totdays = totdays + 366
        else:
            totdays = totdays + 365
        year = year + 1

    if isLeapYear(year2):
        totdays = totdays + (leapcumDays[month2-1] + day2)
    else:
        totdays = totdays + (cumDays[month2-1] + day2)
    return totdays