home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- From: fred@genesis.demon.co.uk (Lawrence Kirby)
- Path: sparky!uunet!pipex!demon!genesis.demon.co.uk!fred
- Subject: Finding the number of days between two dates
- Distribution: world
- References: <1fsk16INNhn0@cs.tut.fi>
- Organization: BT
- Lines: 69
- Date: Tue, 15 Dec 1992 18:31:43 +0000
- Message-ID: <724444303snx@genesis.demon.co.uk>
- Sender: usenet@demon.co.uk
-
-
- In article <1fsk16INNhn0@cs.tut.fi> pjh@cs.tut.fi writes:
-
- >
- >
- >I need to write a standard conforming implementation of a function
- >that computes the number of days between two given dates. For example,
- >given Dec. 6, 1992 and Dec. 24, 1992, the function should return 18.
- >
- >The "obvious" way to do this is to form tm-structures of the two
- >dates, convert them to time_t using mktime(), and then find the
- >difference in seconds using difftime(). However, K&R2 is not explicit
- >about this and I would like to ask a few details:
- >
-
- If the standard time facilities are inadequate for your purposes try the
- following functions which are fairly small and quick!
-
- fromdate() converts a generalised Gregorian date to a relative day count.
- diffdate() takes the difference between 2 relative day counts. For portability
- you're limited to roughly year +/- 32766 although changing all year
- declarations to long should extend that to over +/- 500,000 years with 32 bit
- longs! (Perhaps useful for Fred Flintstone's diary! :-) )
-
- fromdate() returns values relative to some date in year 0 (i.e. 1BC) but the
- precise date doesn't matter since we're only concerned with the difference.
-
-
- /******************************** diffdate() ********************************
- * Calculates the difference in days between 2 dates
- */
-
- static long diffdate(int year1, int month1, int dotm1,
- int year2, int month2, int dotm2 )
-
- {
- return(fromdate(year2, month2, dotm2) - fromdate(year1, month1, dotm1));
- }
-
-
- /******************************** fromdate() ********************************
- * Converts from Gregorian date to Julian days
- */
-
- static long fromdate(int year, int month, int dotm)
-
- {
- long epoque;
-
- month -= 2; /* Make the year start on March 1st (!) */
- if (month < 1) {
- month += 12;
- year--;
- }
-
- epoque = year/400;
- if (epoque*400 > year) /* Ensure negative years are dealt with correctly */
- epoque--;
- year -= epoque*400; /* Now 0 <= year < 400 */
-
- return(epoque*146097L + year*365L + year/4 - year/100 +
- (month*367)/12 + dotm);
- }
-
-
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-