gpt4 book ai didi

c++ - C/C++ : Why the localtime display incorrectly in respect of its timezone?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:48:19 25 4
gpt4 key购买 nike

我最近发现 C 语言有一个奇怪的行为,但不知道为什么会这样。

当我使用 setenv() 时,将 TZ 设置为 GMT+1。本地时间的输出将比 UTC 时间一小时。 (查看输出)

实际上,当我将 TZ 设置为 GMT-1 时。本地时间的输出将比 UTC 时间一小时。

这没有意义。如果你不相信,你可以试试下面的 C 代码。有人知道这种奇怪的行为吗?是bug吗?

代码:

int main(int argc, char** argv)
{
time_t now;
struct tm *local;
setenv("TZ", "GMT+1", 1);
tzset();
now = time(NULL);
//Get the Local time (GMT+1)
local = localtime(&now);
printf("Local time and date: %s\n", asctime(local));
//Get the system time (GMT)
local = gmtime(&now);
printf("UTC time and date: %s\n", asctime(local));
return 0;
}

输出:

Local time and date: Thu Aug  4 14:36:42 2011

UTC time and date: Thu Aug 4 15:36:42 2011

最佳答案

确实很困惑,但不是bug。

POSIX指定这个:

If preceded by a '-', the timezone shall be east of the Prime Meridian; otherwise, it shall be west (which may be indicated by an optional preceding '+' ).

所以,这基本上与您的预期相反。

关于c++ - C/C++ : Why the localtime display incorrectly in respect of its timezone?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944443/

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