Re: function for difference two dates
In article <4c1896cf$0$19000$4fafbaef@reader5.news.tin.it>,
a@b.c.invalid says...
[comp.lang.c,comp.lang.c++]
what about one function that do difference of 2 dates?
where date is class or struct of type
int sec, min, ora, day, mese, anno;
where the difference is in
sec, min, ora, day, mese, anno
#define R return
// res=a-b risultato in sec, min, ora, giorno, mese, anno
int diffDate(Data* res, Data& a, Data& b)
{Data aa, bb;
if(res==0) R 0;
if(a<b) R 0;
if(a==b){res->sec =0; res->min =0; res->ora =0;
res->anno=0; res->mese=0; res->giorno=0;
R 1;
}
aa=a; bb=b;
if(aa.sec>=bb.sec)
res->sec=aa.sec-bb.sec;
else {if(aa.min==0)
{if(aa.ora==0)
{aa=aa-1; // aa meno un giorno [- is operator]
res->ora = 23;
}
else --aa.ora;
res->min=59;
}
else --aa.min;
res->sec=60+aa.sec-bb.sec;
}
if(aa.min>=bb.min)
res->min=aa.min-bb.min;
else {if(aa.ora==0)
{aa=aa-1;
res->ora=23;
}
else --aa.ora;
res->min=60+aa.min-bb.min;
}
if(aa.ora>=bb.ora)
res->ora=aa.ora-bb.ora;
else {aa=aa-1;
res->ora=24+aa.ora-bb.ora;
}
13.14: How can I add N days to a date? How can I find the difference
between two dates?
A: The ANSI/ISO Standard C mktime() and difftime() functions
provide some (limited) 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.
However, these solutions are guaranteed to work correctly only
for dates in the range which can be represented as time_t's.
(For conservatively-sized time_t, that range is often -- but not
always -- from 1970 to approximately 2037; note however that
there are time_t representations other than as specified by Unix
and Posix.) 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 (so don't assume that division by 86400 will be exact).
Another approach to both problems, which will work over a much
wider range of dates, is to use "Julian day numbers". Code for
handling Julian day numbers can be found in the Snippets
collection (see question 18.15c), the Simtel/Oakland archives
(file JULCAL10.ZIP, 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; ISO Secs. 7.12.2.2,7.12.2.3;
H&S Secs. 18.4,18.5 pp. 401-2; David Burki, "Date Conversions".
Most SQL libraries will have extensive date/time libraries as will
several sourceforge projects.