home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mdcbbs!sysjj.mdcbbs.com!lembark
- Newsgroups: comp.lang.c
- Subject: re: find the number difference of dates
- Message-ID: <1992Dec11.103710.1@sysjj.mdcbbs.com>
- From: lembark@sysjj.mdcbbs.com
- Date: 11 Dec 92 10:37:10 GMT
- Organization: EDS Unigraphics, Cypress CA
- Nntp-Posting-Host: vxd1
- Nntp-Posting-User: eschner
- Lines: 58
-
- easiest way to find the difference between two days:
-
- regardless of leapyears, days in the month, etc: there are always 24 hours in
- a day and 3600 sec in a day. another nice trick is that the absolute
- difference of two numbers in a modular base == (a - b + base ) % base (e.g.,
- ( time of day differences: ( hour1 - hour2 + 24 ) % 24 )).
-
- time_t time1, time2;
- time_t n = 3600 * 24, days1 = time1/n, days2 = time2/n;
- time_t max = (time_t)-1/n, diff = (days1 - days2 + maxday) % max;
-
- (time_t)-1 works since time_t is normally an unsigned quantity; (time_t)~0 does
- the same basic thing (32 bits of 0xFFF... will do the same thing).
-
- another approach is to convert both of them to unsigned int's by calculating
- the number of days since a particluar date earlier than both (e.g., 1/1/1900)
- and take the difference of the result:
-
- { /* somewhere in your code: */
- unsigned days1 = nndate( year1, month1, day1 ),
- days2 = nndate( year2, month2, day2 ),
- difference = days1 < days2 ? days2 - days1 : days1 - days2;
- }
-
-
- /*
- convert a year, month and day value to number of days since 1/1/BASE_YEAR,
- obvious choices for BASE_YEAR are 1900 [which wasn't a leap year] or
- 1970. this will only work with julain dates (most of us don't have much
- to do with gregorian dates, however, so that't o.k.).
-
- BASE_YEAR == 1970 => unsigned days has the same time span as
- unsigned long seconds: about 180 years...
- */
- unsigned nndate( unsigned yy, unsigned mm, unsigned dd )
- {
- unsigned nn, i, j;
- unsigned month_days[13][2] =
- { {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} };
-
- for( i = BASE_YEAR, nn=0 ; i < yy ; i++ )
- nn+= 365 + leapyr(i);
-
- i = leapyr( i ); /* save repeated calls to leapyr */
- for( j = 0 ; i < mm ; i++ )
- nn+= month_days[j][i];
-
- nn+= dd;
-
- return nn;
- }
-
- int leapyr( year )
- {
- return ( (!(year%4)&&(year%100) || !(year%400) );
- }
-
-