views:

1526

answers:

2

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.

A: 

A naive approach would be:

Check your start year. If it's a leap year, count the number of days from your current day to December 31 (inclusive). If not, until your starting year equals your ending year, increment the year by 1. Then, check the year. If it is a leap year, start counting days, if not increment the year. Once the current year and ending year are the same, then check to see if the current (== ending) year is a leap year. If it is, count days in months from January to the ending month, otherwise break the algorithm. Once your current month is your ending month, count your days.

Thomas Owens
A: 

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);
      }

     }
}
Plasmer