time.h | time(0) and localtime(time_t) combinations returns previous time if time zone changed in between

621 Views Asked by At

Running the below code as per steps, time(0) and localtime() combinations returns different time.

Versions used - C v60 (visual studio 15)

int main()
{
    time_t t = time(0);      // Line 1
    tm *t2 = localtime(&t);  // Line 2
    //codes                  // Line 3
    time_t t1 = time(0);     // Line 4
    tm *t4 = localtime(&t1); // Line 5
    return 0;
}

Steps:

  • Line 1 - Current time zone UTC+00 - 11.40 am (Before time zone change)
  • Line 2 - Returns UTC +00 - 11.40 am (As Expected)
  • Line 3 - Some other codes. And assume time zone is changed to UTC-01 by some external events. (Time zone Change)
  • Line 4 - As time zone is changed, expected time is UTC-01 - 10.40am.
  • Line 5 - Returns UTC +00 - 11.40 am (Not as expected)

functions _tstrtime() /_strtime() are returning UTC-01 - 10.40 am at Line 4/5 (expected)

Additionally, I've tried using std::time() and std::localtime() from c++, getting the same behaviour

Question : How to get the correct time even when the system's time zone is getting changed in between ?

0

There are 0 best solutions below