6

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

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

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

我知道这可能不是一个常见的情况,但这是测试正在做的测试这个功能,所以他们希望它得到支持!

4

2 回答 2

4

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

从手册页:

描述

tzset() 函数从 TZ 环境变量初始化 tzname 变量。该函数由依赖于时区的其他时间转换函数自动调用。在类似 SysV 的环境中,它还将设置变量时区(格林威治标准时间以西的秒数)和日光(如果该时区没有任何夏令时规则,则为 0,如果一年中有时间进行夏令时,则为非零时间适用)。

如果 TZ 变量未出现在环境中,则 tzname 变量将使用本地挂钟时间的最佳近似值进行初始化,如系统时区目录中的 tzfile(5) 格式文件 localtime 指定(见下文)。(人们也经常看到 /etc/localtime 在这里使用,一个指向系统时区目录中正确文件的符号链接。)

一个简单的测试:

#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 2012 年 1 月 11 日星期三 12:35:02

tz: EST - EDT 2012 年 1 月 11 日星期三 13:35:02

于 2012-01-11T18:38:25.527 回答
1

There's nothing in the standard library to do this. Unless your platform offers some extension to the library for updating the time zone, your program's calls to localtime() will probably always use the time zone that was active at program start up.

You could probably work around that by putting the localtime stuff in a separate process that your main program can startup and shutdown at will, thus re-initializing that process's time zone.

Or instead your platform may offer some other API for getting the local time that will reflect changes in the system time zone.

于 2012-01-11T18:04:58.787 回答