Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

c++ - 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") ); 

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...