Conversion to UTC timezone in C++ leaves the time intact (regardless of the original timezone)

215 Views Asked by At

I am working with a dataset that contains the following information: date and time in the form "yyyy-mm-dd", "hh:mm". It also contains the name of the US state where the time has been measured. My goal is to unify all the time measurements so that they are all in the UTC timezone. I have written a code that doesn't work and I don't intend to go through the details of that code. However, in order to check why my code doesn't work, I have written a simple test that also doesn't work. The test is as follows:

I have tried to convert "Friday January 1 2021 9:00 AM California" to its equivalent UTC time which is "Friday January 1 2021 5:00 PM". The code snippet for conversion comes in the following:

struct tm calTM; 
calTM.tm_hour = 9;
calTM.tm_min = 0;   
calTM.tm_year = 2021-1900; 
calTM.tm_mon = 1-1;
calTM.tm_mday = 1;
calTM.tm_isdst = -1;

setenv("TZ", "America/California", 1);
time_t calTime = mktime(&calTM);
unsetenv("TZ");

struct tm* utcTime;
utcTime = gmtime(&calTime);
cout << "UTC hh: " << utcTime->tm_hour << ", UTC mm: " << utcTime->tm_min; 
cout << ", UTC year: " << utcTime->tm_year << ", UTC month: " << utcTime->tm_mon << ", UTC day: " << utcTime->tm_mday << endl;

Instead of producing the expected result (Friday January 1 2021 5:00 PM), the code snippet above produces the following result:

UTC hh: 9, UTC mm: 0, UTC year: 121, UTC month: 0, UTC day: 1

which is "month 0, day 1, year 121, 9:00 AM". Year and month are fixed after passing utcTime to the mktime() function. After adding the lines

time_t utc_time_t = mktime(utcTime);
cout << ctime(&utc_time_t) << endl;

the output is

Fri Jan  1 09:00:00 2021

Still, the time (hh:mm:ss) is wrong (exactly the same as in the original timezone). Could you please help me figure out the problem with my code? Thank you very much!

0

There are 0 best solutions below