home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_11_02 / 1102124b < prev    next >
Text File  |  1992-12-10  |  1KB  |  52 lines

  1. // date.cpp: Implement the Date class
  2.  
  3. #include "date.h"
  4.  
  5. inline int isleap(int y)
  6.   {return y%4 == 0 && y%100 != 0 || y%400 == 0;}
  7.  
  8. static int Dtab[2][13] =
  9. {
  10.   {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  11.   {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  12. };
  13.  
  14. Date * Date::interval(const Date& d2)
  15. {
  16.     static Date result;
  17.     int months, days, years, prev_month;
  18.  
  19.     // Compute the interval - assume d1 precedes d2
  20.     years = d2.year - year;
  21.     months = d2.month - month;
  22.     days = d2.day - day;
  23.  
  24.     // Do obvious corrections (days before months!)
  25.     //
  26.     // This is a loop in case the previous month is
  27.     // February, and days < -28.
  28.     prev_month = d2.month - 1;
  29.     while (days < 0)
  30.     {
  31.         // Borrow from the previous month
  32.         if (prev_month == 0)
  33.             prev_month = 12;
  34.         --months;
  35.         days += Dtab[isleap(d2.year)][prev_month--];
  36.     }
  37.  
  38.     if (months < 0)
  39.     {
  40.         // Borrow from the previous year
  41.         --years;
  42.         months += 12;
  43.     }
  44.  
  45.     /* Prepare output */
  46.     result.month = months;
  47.     result.day = days;
  48.     result.year = years;
  49.     return &result;
  50. }
  51.  
  52.