2016-03-04 192 views
0

我写了一个类Instant管理与时区和一些夏令时算法(EuropeUSA)有关的日期和时间。 到目前为止,我让这个类的用户指定DST算法作为默认值Europe。但现在我想自动检测它的默认值。检测夏令时算法

这是我第一次实施。它似乎在我的Windows 7工作站(编译器:英特尔14.0)(我有理由必须澄清列表),但它不适用于Linux openSUSE(编译器:gcc 4.8.3),因为tz.tz_dsttime始终是0.

typedef enum { 
    DST_ALGO_NONE = 0, 
    DST_ALGO_EUROPE = 1, 
    DST_ALGO_USA = 2 
} TimeZoneType; 

TimeZoneType auto_detect_dst_algorithm() 
{ 
# ifdef WIN32 
     TIME_ZONE_INFORMATION tz; 
     GetTimeZoneInformation(&tz); 
     std::wstring tz_wstr = tz.DaylightName; 
     std::string tz_str(tz_wstr.begin(), tz_wstr.end()); 
     if( tz_str.find("Romance") != std::string::npos 
      || tz_str.find("RST") != std::string::npos 
      || tz_str.find("Central Europe") != std::string::npos 
      || tz_str.find("CEST") != std::string::npos 
      || tz_str.find("Middle Europe") != std::string::npos 
      || tz_str.find("MET") != std::string::npos 
      || tz_str.find("Western Europe") != std::string::npos 
      || tz_str.find("WET") != std::string::npos) 
     { 
      return DST_ALGO_EUROPE; 
     } 
     else if( tz_str.find("Pacific") != std::string::npos 
       || tz_str.find("PDT") != std::string::npos) 
     { 
      return DST_ALGO_USA; 
     } 
     else 
     { 
      return DST_ALGO_NONE; 
     } 
# else 
     struct timeval tv; 
     struct timezone tz; 
     gettimeofday(&tv, &tz); 
     if(tz.tz_dsttime == 1) 
     { 
      return DST_ALGO_USA; 
     } 
     else if(tz.tz_dsttime == 3 || tz.tz_dsttime == 4) 
     { 
      return DST_ALGO_EUROPE; 
     } 
     else 
     { 
      return DST_ALGO_NONE; 
     } 
# endif 
} 

这样做的好方法是什么?

+7

“这样做的好方法是什么?”使用图书馆!!!!!严重的时区不是你想要做的事情。 – Mat

+0

是的,我想要。这个问题呢? – Caduchon

+2

给一个理智的理由。 –

回答

1

the gettimeofday man page

在Linux上,用glibc,结构时区tz_dsttime字段的设置从未被settimeofday()gettimeofday()使用。因此,以下纯粹是历史利益。

在旧系统中,场tz_dsttime包含符号常量...

...当然,事实证明,在夏令时是有效的期间不能用一个简单的算法给出一个每个国家;事实上,这个时期是由不可预测的政治决定决定的。 所以这种表示时区的方法已经被废弃

原始问题中的评论是正确的。你不应该试图自己实现这一点,特别是使用一个废弃的API。

即使在示例代码的Windows部分中,您也对DaylightName字段中可能找到的内容做了很多假设。你知道有更多的时区比你测试的更多,对吗?而且,在用户选择除英语之外的主要语言的系统上,这些字符串会显得不同。

C++有很多好的时区库。任何有价值的东西都将使用the IANA tz database作为它的来源。我会仔细看看the best practices FAQthe timezone tag wiki。特别是,FAQ建议使用CCTZ,ICUTZ,并警告不要使用Boost来实现此功能。