Pergunta

Here is the function

time_t time_from_string(const char* timestr)
{
    if (!timestr)
        return 0;

    struct tm t1;
    memset(&t1, 0, sizeof(t1));
    int nfields = sscanf(timestr, "%04d:%02d:%02d %02d:%02d:%02d", 
                  &t1.tm_year, &t1.tm_mon, &t1.tm_mday, &t1.tm_hour, 
                  &t1.tm_min, &t1.tm_sec);
    if (nfields != 6)
        return 0;

    t1.tm_year -= 1900;
    t1.tm_mon--;
    t1.tm_isdst = -1; // mktime should try itself to figure out what DST was

    time_t result = mktime(&t1);
    return result;
}

When I call it with the argument "2007:11:14 11:19:07", it returns 1195028347 in Linux (Ubuntu 12.04, gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3) and 1195024747 in Windows (windows 7, Visual Studio 2010).

As can be seen, time difference is 3600.

I run both operating systems on the same computer (dual-boot), which is in the MSK time zone. Both OSes are synchronized with the internet time, and their system clock show correct time.

When I call this function with another argument, "2012:08:21 18:20:40", I get 1345558840 in both systems.

Why does the results differ in several cases?

EDIT Forgot to mention. I control the contents of the t1 variable after call to mktime().

In both systems:

t1.tm_sec = 7;
t1.tm_min = 19;
t1.tm_hour = 11;
t1.tm_mday = 14;
t1.tm_mon = 10;
t1.tm_year = 107;
t1.tm_wday = 3;
t1.tm_yday = 317;

t1.tm_isdst = 0;

Please, mention the last line. Both systems determine that there is no daylight savings in effect.

Linux additionally shows the following fields in struct tm:

t1.gmtoff = 10800;
t1.tm_zone = "MSK";
Foi útil?

Solução

From Wikipedia: Moscow Time

Until 2011, during the winter, between the last Sunday of October and the last Sunday of March, Moscow Standard Time (MSK, МСК) was 3 hours ahead of UTC, or UTC+3; during the summer, Moscow Time shifted forward an additional hour ahead of Moscow Standard Time to become Moscow Summer Time (MSD), making it UTC+4.

In 2011, the Russian government proclaimed that daylight saving time would in future be observed all year round, thus effectively displacing standard time—an action which the government claimed emerged from health concerns attributed to the annual shift back-and-forth between standard time and daylight saving time. On 27 March 2011, Muscovites set their clocks forward for a final time, effectively observing MSD, or UTC+4, permanently.

Since Moscow observed winter time (UTC+3) on 2007-11-14, 11:19:07 MSK was 08:19:07 UTC, and the Unix timestamp was 1195028347.

It looks like the value you get on Linux is correct, and the value you get on Windows seems to assume UTC+4 which is incorrect.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top