Listing 2 Implements the interval and compare member functions

// date4.cpp

#include "date4.h"

inline int isleap(int y)
  {return y%4 == 0 && y%100 != 0 || y%400 == 0;}

static int dtab[2][13] =
{
  {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

Date * Date::interval(const Date& d2) const
{
   static Date result;
   int months, days, years, prev_month;

   // Compute the interval - assume d1 precedes d2
   years = d2.year - year;
   months = d2.month - month;
   days = d2.day - day;

   // Do obvious corrections (days before months!)
   //
   // This is a loop in case the previous month is
   // February, and days < -28.
   prev_month = d2.month - 1;
   while (days < 0)
   {
      // Borrow from the previous month
      if (prev_month == 0)
         prev_month = 12;
      -months;
      days += dtab[isleap(d2.year)][prev_month-];
   }

   if (months < 0)
   {
      // Borrow from the previous year
      -years;
      months += 12;
   }

   // Prepare output
   result.month = months;
   result.day = days;
   result.year = years;
   return &result;
}

int Date::compare(const Date& d2) const
{
   int months, days, years, order;

   years = year - d2.year;
   months = month - d2.month;
   days = day - d2.day;

   // return <0, 0, or >0, like strcmp()
   if (years == 0 && months == 0 && days == 0)
      return 0;
   else if (years == 0 && months == 0)
      return days;
   else if (years == 0)
      return months;
   else
      return years;
}
// End of File