如何获取当前时区? [英] How to get the current time zone?
问题描述
在大多数我见过的例子:
In most of the examples I had seen:
time_zone_ptr zone( new posix_time_zone("MST-07") );
但我只是想获得当前时区为运行code机器。我不想硬code中的时区名称。
But I just want to get the current time zone for the machine that runs the code. I do not want to hard code the time zone name.
推荐答案
普通POSIX:的调用tzset,使用TZNAME 。
#include <ctime>
tzset();
time_zone_ptr zone(new posix_time_zone(tzname[localtime(0)->tm_isdst]));
Posix的使用的glibc / BSD 补充:
time_zone_ptr zone(new posix_time_zone(localtime(0)->tm_zone));
以上的缩写的Posix时区,定义方面UTC的偏移量,并随着时间的推移(有一个更长的形式可以包括DST的过渡,而不是政治和历史变迁)。
The above are abbreviated Posix timezones, defined in terms of offset from UTC and not stable over time (there's a longer form that can include DST transitions, but not political and historical transitions).
ICU 是便携和具有逻辑检索系统时区为奥尔森时区(由 sumwale 片段):
ICU is portable and has logic for retrieving the system timezone as an Olson timezone (snippet by sumwale):
// Link with LDLIBS=`pkg-config icu-i18n --libs`
#include <unicode/timezone.h>
#include <iostream>
using namespace U_ICU_NAMESPACE;
int main() {
TimeZone* tz = TimeZone::createDefault();
UnicodeString us;
std::string s;
tz->getID(us);
us.toUTF8String(s);
std::cout << "Current timezone ID: " << s << '\n';
delete tz;
}
在Linux中,ICU实施要与tzset兼容和和 TZ http://freedesktop.org/software/systemd/man /localtime.html相对=nofollow> 的/ etc /本地时间
,其中最近的Linux系统是specced是包含奥尔森标识一个符号链接(< A HREF =http://stackoverflow.com/a/28069672/229753>这里的记录)。参见 uprv_tzname
的实施细节。
On Linux, ICU is implemented to be compatible with tzset and looks at TZ
and /etc/localtime
, which on recent Linux systems is specced to be a symlink containing the Olson identifier (here's the history). See uprv_tzname
for implementation details.
升压不知道如何使用奥尔森标识符。你可以建立一个的posix_time_zone
使用非DST和DST偏移,但在这一点上,最好使用ICU执行,以保持。见<一href=\"http://www.boost.org/doc/libs/1_57_0/libs/locale/doc/html/dates_times_timezones.html#dates_times_timezones_qna\"相对=nofollow>这个升压常见问题解答。
Boost doesn't know how to use the Olson identifier. You could build a posix_time_zone
using the non-DST and DST offsets, but at this point, it's best to keep using the ICU implementation. See this Boost FAQ.
这篇关于如何获取当前时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!