这是函数
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";
最佳答案
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/