gpt4 book ai didi

更改时区时的 c++ localtime

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:41:13 26 4
gpt4 key购买 nike

我有一个使用 localtime() 的设置来获取一个带有本地时间的 tm。这一切都很好。

但是,如果我在应用程序运行时更改时区,它不会注意到我更改了时区。

有没有办法告诉它“再看一遍”以刷新到系统时区?

我知道这可能不是常见情况,但这是测试此功能的测试方式,因此他们希望支持它!

最佳答案

看看 tzset(这只是 posix)。这可能会给你你所需要的。如果您的 TZ 环境变量未设置,它应该从操作系统重新初始化。

来自手册页:

DESCRIPTION

The tzset() function initializes the tzname variable from the TZ environment variable. This function is automatically called by the other time conversion functions that depend on the time zone. In a SysV-like environment it will also set the variables timezone (seconds West of GMT) and daylight (0 if this time zone does not have any daylight savings time rules, non-zero if there is a time during the year when daylight savings time applies).

If the TZ variable does not appear in the environment, the tzname variable is initialized with the best approximation of local wall clock time, as specified by the tzfile(5)-format file localtime found in the system timezone directory (see below). (One also often sees /etc/localtime used here, a symlink to the right file in the system timezone directory.)

一个简单的测试:

#include <iostream>
#include <time.h>
#include <stdlib.h>

int main()
{
tzset();

time_t t;
time(&t);

std::cout << "tz: " << tzname[0] << " - " << tzname[1] << " " << ctime(&t) << std::endl;

setenv("TZ", "EST5EDT", 1);
tzset();

std::cout << "tz: " << tzname[0] << " - " << tzname[1] << " " << ctime(&t) << std::endl;

return 0;
}

给我输出:

tz: CST - CDT Wed Jan 11 12:35:02 2012

tz: EST - EDT Wed Jan 11 13:35:02 2012

关于更改时区时的 c++ localtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8824156/

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