I am trying to encode the current utc time into a string using the strftime
function:
time_t now; struct tm nowLocal; struct tm nowUtc; now = time(NULL); localtime_r(&now, &nowLocal); gmtime_r(&now, &nowUtc);
So far so good: nowLocal
contains the current time in my time zone (CET), nowUtc
contains the utc time, the difference exactly matches the value of tm_gmtoff
:
nowLocal: {tm_sec = 28, tm_min = 27, tm_hour = 13, tm_mday = 23, tm_mon = 4, tm_year = 112, tm_wday = 3, tm_yday = 143, tm_isdst = 1, tm_gmtoff = 7200, tm_zone = 0x8127a38 "CEST"} nowUtc: {tm_sec = 28, tm_min = 27, tm_hour = 11, tm_mday = 23, tm_mon = 4, tm_year = 112, tm_wday = 3, tm_yday = 143, tm_isdst = 0, tm_gmtoff = 0, tm_zone = 0x3e9907 "GMT"}
Then I call strftime()
with the format "%s"
to get seconds from the era:
char tsFromLocal[32]; char tsFromUtc[32]; strftime(tsFromLocal, sizeof(tsFromLocal), "%s", &nowLocal); strftime(tsFromUtc, sizeof(tsFromUtc), "%s", &nowUtc);
The result seems strange to me. I expected to get exactly the same string from both strftime()
calls, as the %s
format is described as:
The number of seconds since an era, i.e. from 1970-01-01 00:00:00 UTC
. Seconds of seconds are not counted if there is no support of the second level.
But I have two different meanings:
tsFromLocal:"1337772448" tsFromUtc: "1337768848"
and, in addition, the difference is not 7200 ( tm_gmtoff
), but 3600 . Can someone explain this behavior? Or is this a mistake?
The reason I do this is because I need to transfer the time value over the network and compare it with the current time on the target machine, which may be in different time zones. On the target machine, I wanted:
struct tm restoredUtc; time_t restored; strptime(tsFromUtc, "%s", &restoredUtc); restored = timegm(&restoredUtc);
But I got:
restoredUtc:{tm_sec = 28, tm_min = 27, tm_hour = 12, tm_mday = 23, tm_mon = 4, tm_year = 112, tm_wday = 3, tm_yday = 143, tm_isdst = 1, tm_gmtoff = 7200, tm_zone = 0x8127a38 "CEST"}
So strptime()
sets tm_zone
according to the current tm_zone
. But even if I used timelocal()
instead of timegm()
, I wonβt get the correct value, since it should be 11:27:28 CEST and not 12:27:28 CEST . Is this error related to different strftime()
results?
Any comments on this later part?