Home > Net >  mkTime() function does not pick correct timezone c
mkTime() function does not pick correct timezone c

Time:11-22

I am getting an input date from user and convert it into tm struct, (setting is_dst, timezone and gmtoff parameters of tm struct using local time), but when I am using mkTime to get epoch value it changes the timezone and gmtOffset property of tm struct and return the wrong offset value.

tm tmStartDateTime = {};
string dateString = inputDate;            
if (myclass::tryParseString(inputDate, "%Y/%m/%d %H:%M:%S", tmStartDateTime))// converting string date to tm
{                
   struct timespec now = {0};
   clock_gettime(CLOCK_REALTIME, &now);
   tm *nowStruct = localtime(&now.tv_sec);

   // setting isdst, gmtoff and timezone using localtime
   tmStartDateTime.tm_isdst = nowStruct->tm_isdst; 
   tmStartDateTime.tm_gmtoff = nowStruct->tm_gmtoff; 
   tmStartDateTime.tm_zone = nowStruct->tm_zone;                
                
   tm bmStartDate = {};                 
   bmStartDate = tmStartDateTime;
                               
   StartDateTimeEpoch = mktime(&bmStartDate);
}

for e.g. if user gives a date 01/01/1970 00:00:00 and machine timezone is set to Europe/London, then tm struct gmtoffset value changes to 3600 and timezone changes to BST whereas the machine timezone is GMT with 0 gmtoffset as daylight saving is ended on 30th oct 2022. Why and How mktime is changing timezone and gmtoffset value of tm struct. (Note: TZ variable of machine is set to empty string, i have also change that to Europe/London but with no luck)

CodePudding user response:

localtime() is using the DST setting for the time you passed to it, not the current time when the function is called. DST was in effect in the UK on 1 Jan 1970, so it will return summer time regardless of whether DST is in effect today.

  • Related