linux - 有时 mktime 在 Windows 和 Linux 中的结果不同

标签 linux windows mktime

这是函数

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;
}

当我用参数“2007:11:14 11:19:07”调用它时,它在Linux(Ubuntu 12.04,gcc(Ubuntu/Linaro 4.6.3-1ubuntu5)4.6.3)中返回1195028347,在Linux中返回1195024747 Windows(Windows 7、Visual Studio 2010)。

可以看出,时间差为3600。

我在同一台计算机上运行两个操作系统(双启动),该计算机位于 MSK 时区。 两个操作系统都与互联网时间同步,并且其系统时钟显示正确的时间。

当我使用另一个参数“2012:08:21 18:20:40”调用此函数时,我在两个系统中都得到 1345558840。

为什么在几种情况下结果会有所不同?

编辑 忘记说了。我在调用 mktime() 后控制 t1 变量的内容。

在两个系统中:

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;

请提及最后一行。两个系统都确定没有有效的夏令时。

Linux 在 struct tm 中还显示了以下字段:

t1.gmtoff = 10800;
t1.tm_zone = "MSK";

最佳答案

来自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.

由于莫斯科于 2007 年 11 月 14 日实行冬令时 (UTC+3),11:19:07 MSK 为 08:19:07 UTC,Unix 时间戳为 1195028347。

看起来您在 Linux 上获得的值是正确的,而您在 Windows 上获得的值似乎假设 UTC+4,这是不正确的。

关于linux - 有时 mktime 在 Windows 和 Linux 中的结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18983742/

相关文章:

c# - Linux/C++ 程序员到 C#/Windows 程序员

java - Windows 端口的最大积压值

c++ - 错误的计数器路径,pdhAddCounter; Windows 中的性能监视器

php - 格式化日期的问题

php - 为什么 php 时间戳会这样? 1985 年 11 月 3 日

PHP - mktime 在 mysql 中存储错误的日期

c - 设置 TCP_QUICKACK 和 TCP_NODELAY

linux - 在 Ubuntu 中哪里可以找到 libopenexr.so?

regex - 使用正则表达式获取命令列表

linux - 使用 wget 下载 shtml 页面上的所有 zip 文件