Plain posix: call tzset, use tzname.
#include <ctime>
tzset();
time_zone_ptr zone(new posix_time_zone(tzname[localtime(0)->tm_isdst]));
Posix with glibc/bsd additions:
time_zone_ptr zone(new posix_time_zone(localtime(0)->tm_zone));
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 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 << '
';
delete tz;
}
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.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…