c++ - 如何获取当前时区?

标签 c++ boost timezone boost-date-time

在我见过的大多数例子中:

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

但我只想获取运行代码的机器的当前时区。我不想硬编码时区名称。

最佳答案

普通 posix:call tzset, use 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 timezones ,根据与 UTC 的偏移量来定义,并且随着时间的推移不稳定(有更长的形式可以包括 DST 转换,但不包括政治和历史转换)。

ICU是可移植的,并且具有将系统时区检索为 Olson 时区的逻辑(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/etc/localtime ,在最近的 Linux 系统上,它被指定为包含 Olson 标识符 (here's the history) 的符号链接(symbolic link)。实现细节见 uprv_tzname

Boost 不知道如何使用 Olson 标识符。您可以使用非 DST 和 DST 偏移量构建 posix_time_zone,但此时最好继续使用 ICU 实现。见 this Boost FAQ .

关于c++ - 如何获取当前时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2136970/

相关文章:

c++ - 使用 C++ 将 HTML 转换为纯文本

c++ - 模板类中使用了错误的构造函数

c++ - 如何从字符串中解析日期/时间?

php - 在 laravel 中动态更改时区

javascript - 如何在 JavaScript 上检查日期和时间?

c++ - boost asio 示例编译错误

c++ - boost::xpressive 查看序列的开头

c++ - 相当于Boost.Format的C++ 11

php - 将MySQL日期时间转换为不同时区

c++ - 在集群上使用 OpenMP