How can I add n days to a date? How can I find the difference between two dates?
The ANSI/ISO Standard C mktime and difftime functions provide some support for both problems. mktime accepts non-normalized dates, so it is straightforward to take a filled-in struct tm, add or subtract from the tm_mday field, and call mktime to normalize the year, month, and day fields (and incidentally convert to a time_t value). difftime computes the difference, in seconds, between two time_t values; mktime can be used to compute time_t values for two dates to be subtracted.
These solutions are only guaranteed to work correctly for dates in the range which can be represented as time_t's. The tm_mday field is an int, so day offsets of more than 32,736 or so may cause overflow. Note also that at daylight saving time changeovers, local days are not 24 hours long.
Another approach to both problems is to use ``Julian day'' numbers. Implementations of Julian day routines can be found in the file JULCAL10.ZIP from the Simtel/Oakland archives (see question 18.16) and the ``Date conversions'' article mentioned in the References.
See also questions 13.13, 20.31, and 20.32.
References:
K&R2 Sec. B10 p. 256
ANSI Secs. 4.12.2.2,4.12.2.3
ISO Secs. 7.12.2.2,7.12.2.3
H&S Secs. 18.4,18.5 pp. 401-2
David Burki, ``Date Conversions''
Read sequentially: prev next up top
This page by Steve Summit // Copyright 1995 // mail feedback