Search code examples
algorithmleap-year

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


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.


Solution

  • Here's my pseudo code version using your functions for - is_leap_year, days_between. As a commenter noted, these are tricky functions to write correctly.

    int leap_year_days_between(Date d1, Date d2) {
    
       if (d1.year == d2.year) {
           if (is_leap_year(d1.year) { return days_between(d1,d2); } 
           else { return 0; }
        }
        else {
          Date last_day_in_year(12, 31, d1.year);
          int count=0;
          Date tmp = d1;
          while (tmp.year < d2.year) {
             if ( is_leap_year(tmp.year) ) {
                 count += days_between(tmp,last_day_in_year);
              }
              tmp = (1, 1, tmp.year+1);
          }
          if ( is_leap_year(d2.year) ) {
             count += days_between(tmp, d2);
          }
    
         }
    }