【发布时间】:2018-01-17 16:54:17
【问题描述】:
我正在尝试将time_t 变量中保存的时间转换为某个时区中的struct tm*,该时区不是本地时区。
在this post 的基础上,讨论了从struct tm* 到time_t 的逆运算,我编写了以下函数:
struct tm* localtime_tz(time_t* t, std::string timezone) {
struct tm* ret;
char* tz;
tz = std::getenv("TZ"); // Store currently set time zone
// Set time zone
setenv("TZ", timezone.c_str(), 1);
tzset();
std::cout << "Time zone set to " << std::getenv("TZ") << std::endl;
ret = std::localtime(t); // Convert given Unix time to local time in time zone
std::cout << "Local time is: " << std::asctime(ret);
std::cout << "UTC time is: " << std::asctime(std::gmtime(t));
// Reset time zone to stored value
if (tz)
setenv("TZ", tz, 1);
else
unsetenv("TZ");
tzset();
return ret;
}
但是,转换失败,我得到了
Time zone set to CEST
Local time is: Wed Aug 9 16:39:38 2017
UTC time is: Wed Aug 9 16:39:38 2017
即本地时间设置为 UTC 时间,而不是 CEST 的 UTC+2。
【问题讨论】: