home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-387-Vol-3of3.iso / c / cuj9301.zip / 1101117B < prev    next >
Text File  |  1992-11-19  |  1KB  |  52 lines

  1. /* date_int.c: Compute duration between two dates */
  2.  
  3. #include "date.h"
  4.  
  5. #define isleap(y) \
  6.   ((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 *d1, 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 - d1->year;
  21.     months = d2->month - d1->month;
  22.     days = d2->day - d1->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.      */
  29.     prev_month = d2->month - 1;
  30.     while (days < 0)
  31.     {
  32.         /* Borrow from the previous month */
  33.         if (prev_month == 0)
  34.             prev_month = 12;
  35.         --months;
  36.         days += Dtab[isleap(d2->year)][prev_month--];
  37.     }
  38.  
  39.     if (months < 0)
  40.     {
  41.         /* Borrow from the previous year */
  42.         --years;
  43.         months += 12;
  44.     }
  45.  
  46.     /* Prepare output */
  47.     result.month = months;
  48.     result.day = days;
  49.     result.year = years;
  50.     return &result;
  51. }
  52.