2016-03-04 191 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來實現此功能。