I have one struct tm.
And I need to add some fixed interval (given in xx years, xx months, xx days)
to the tm struct.
Is there any standard functio
The other answers lead to highly unstable results depending on how your system initializes struct tm and whether mid-day time values were initialized properly.
If all you are interested in is changes in the date, while the time remains the same, then set tm_isdst
, tm_hour
, tm_sec
all to 0 before passing to mktime
. Better yet, grab their values before and reset them after for consistency (and if they were inconsistent before, they'll consistently remain so). Reusing code from other answers:
tm addinterval(tm t, int y, int m, int d)
{
auto hour = t.tm_hour;
auto min = t.tm_min;
auto sec = t.tm_sec;
// First we discover the DST Flag. By setting hour to 12
// we can assure the mktime does not shift the date
// because it will shift the hour!
t.tm_isdst = 0;
t.tm_hour = 12;
t.tm_min = 0;
t.tm_sec = 0;
mktime(&t);
// Now we can add the interval
t.tm_year += y;
t.tm_mon += m;
t.tm_mday += d;
mktime(&t);
// Now reset the mid-day time values
t.tm_hour = hour;
t.tm_min = min;
t.tm_sec = sec;
// Return struct tm while keeping mid-day time the same
// while the only values that changed are the date and perhaps isdst.
return t;
}
I wish it was simpler, but that's just how it has to be.