gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:55:13 25 4
gpt4 key购买 nike

这是函数

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)和 1195024747 中返回 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 - 有时在 windows 和 linux 中 mktime 的结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18983742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com