How do I find the current system timezone?

后端 未结 12 473
攒了一身酷
攒了一身酷 2020-11-30 06:22

On Linux, I need to find the currently configured timezone as an Olson location. I want my (C or C++) code to be portable to as many Linux systems as possible.

For e

12条回答
  •  孤街浪徒
    2020-11-30 07:05

    Pretty late in the day, but I was looking for something similar and found that ICU library has the provision to get the Olson timezone ID: http://userguide.icu-project.org/datetime/timezone

    It is now installed on most linux distributions (install the libicu-dev package or equivalent). Code:

    #include 
    #include 
    
    using namespace U_ICU_NAMESPACE;
    
    int main() {
      TimeZone* tz = TimeZone::createDefault();
      UnicodeString us;
      tz->getID(us);
      std::string s;
      us.toUTF8String(s);
      std::cout << "Current timezone ID: " << s << '\n';
      delete tz;
    
      return 0;
    }
    

    And to get the abbreviated/POSIX timezone names (should also work on Windows):

    #include 
    
    int main() {
      time_t ts = 0;
      struct tm t;
      char buf[16];
      ::localtime_r(&ts, &t);
      ::strftime(buf, sizeof(buf), "%z", &t);
      std::cout << "Current timezone (POSIX): " << buf << std::endl;
      ::strftime(buf, sizeof(buf), "%Z", &t);
      std::cout << "Current timezone: " << buf << std::endl;
    

提交回复
热议问题