Addition some interval to tm structs

StNickolay picture StNickolay · Nov 18, 2010 · Viewed 11.5k times · Source

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 function to do this?

The compiler I use is MSVC 2005 on Windows XP.

Answer

Vovanium picture Vovanium · Nov 18, 2010

There are two functions which convert time formats:

  1. mktime() which converts struct tm (representing local time) to time_t.
  2. localtime() which converts time_t to local time in struct tm.

Interesing is the first one, which accepts out-of-range struct member values and as a side-product of conversion set them (and all others) appropriately. This may be used to correct field data values after arithmetic operations. However type of fields is int, so there may be an overflow (on 16 bit system), if e. g. you add number of seconds in the year.

So if you want to have actual dates this code would help (modified copy of answer from @pmg):

struct tm addinterval(struct tm x, int y, int m, int d) {
    x.tm_year += y;
    x.tm_mon += m;
    x.tm_mday += d;
    mktime(&x);
    return x;
}

Also note about tm_isdst member, care about it. Its value may cause time to shift forth and back when you jump over daylight time switch dates.