Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

timezone

dst

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.


If on Windows, you don't have timegm() available to you:

struct tm *tptr;
time_t secs, local_secs, gmt_secs;
time( &secs );  // Current time in GMT
// Remember that localtime/gmtime overwrite same location
tptr = localtime( &secs );
local_secs = mktime( tptr );
tptr = gmtime( &secs );
gmt_secs = mktime( tptr );
long diff_secs = long(local_secs - gmt_secs);

or something similar...


If you need to worry about converting date/time with timezone rules, you might want to look into ICU.