如何获得当前时区?

Che*_*eng 28 c++ timezone boost boost-date-time

在我看到的大多数例子中:

time_zone_ptr zone( new posix_time_zone("MST-07") ); 
Run Code Online (Sandbox Code Playgroud)

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

Tob*_*obu 10

普通posix:调用tzset,使用tzname.

#include <ctime>
tzset();
time_zone_ptr zone(new posix_time_zone(tzname[localtime(0)->tm_isdst]));
Run Code Online (Sandbox Code Playgroud)

Posix与glibc/bsd的补充:

time_zone_ptr zone(new posix_time_zone(localtime(0)->tm_zone));
Run Code Online (Sandbox Code Playgroud)

以上是缩写的Posix时区,根据与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;
}
Run Code Online (Sandbox Code Playgroud)

在Linux上,ICU被实现为与tzset兼容并查看,TZ并且/etc/localtime在最近的Linux系统上被称为包含Olson标识符的符号链接(这是历史记录).有关uprv_tzname实施细节,请参阅

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

  • 我无法代替其他环境,但MSVS 2008的`_get_tzname()`实现返回一个名称,如"太平洋标准时间"; Boost的`posix_time_zone`需要像"PST"这样的东西.另外,btw,`tzname`(POSIX,标准称它为`_tzname`)是一个2-D char数组.[MSVC还提供了一个`TZNAME_MAX`,如果你#define _POSIX_`,但设置为10,显然是对早期实现的疏忽. (3认同)

amp*_*ine 1

好吧,也许你可以使用 GeoIP 库来做到这一点。我知道这有点矫枉过正,但由于世界上大多数计算机都连接到互联网,因此您可能会侥幸逃脱。据我正在开发的人说,它的准确率超过 99%。

注意:这是一个愚蠢的想法。我只是在寻求答案。

  • 是的,虽然很蠢,但是很有创意! (3认同)