How to get the current time zone?

前端 未结 5 1589
不知归路
不知归路 2020-12-06 09:03

In most of the examples I had seen:

time_zone_ptr zone( new posix_time_zone(\"MST-07\") ); 

But I just want to get the current time zone fo

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 09:47

    Plain posix: call tzset, use tzname.

    #include 
    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 
    #include 
    
    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;
    }
    

    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.

提交回复
热议问题