我試圖將某個變量time_t
中的時間轉換爲struct tm*
,該時間不是本地時區。C++:將Unix時間轉換爲非本地時區
大廈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。