Wednesday, May 18, 2011

Convert time between timezones

What to do if we want convert time between two timezones?

For example, an event occured at 15-00 by Moscow time(UTC+4). By that time, in Omsk(UTC+7) there is 18-00, three hours "more". We want to show time of event using local Omsk time.

How to do that in C++?

Fill tmDateExternal structure of type tm, with source event time(15-00). Save timezone shift of Moscow to in nSrcTZ, it is obviously 4.
__time64_t t64date = _mkgmtime64(&tmDateExternal) - nSrcTZ*60*60;
tm tmDateLocal;
_localtime64_s( &tmDateLocal, &t64date );

Now you have local Omsk time for that event in tmDateLocal structure.