Converting Between Local Times and GMT/UTC in C/C++

You’re supposed to use combinations of gmtime/localtime and timegm/mktime. That should give you the orthogonal tools to do conversions between struct tm and time_t.

For UTC/GMT:

time_t t;
struct tm tm;
struct tm * tmp;
...
t = timegm(&tm);
...
tmp = gmtime(t);

For localtime:

t = mktime(&tm);
...
tmp = localtime(t);

All tzset() does is set the internal timezone variable from the TZ environment variable. I don’t think this is supposed to be called more than once.

If you’re trying to convert between timezones, you should modify the struct tm‘s tm_gmtoff.

Leave a Comment