2013-03-02 55 views
2

我有一個城市列表(紐約,倫敦等),我需要做一些時區轉換,但我看到大多數API要求您知道時區名稱(如東部標準時間,東京標準時間等)。在C#中是否有將城市名稱轉換爲其TimeZone名稱(東京 - >東京標準時間)?

無論如何將城市名稱轉換爲其適當的TimeZone名稱? (通過紐約,並返回「東部標準時間」)

+0

您可以使用lat/long查詢此webservice:http://www.earthtools.org/webservices.htm#timezone,它將返回XML,其中包含其時區 – 2013-03-02 06:21:49

+1

請注意,所有給出的響應都將幫助您IANA/Olson時區標識符。這些與.net中的'TimeZoneInfo'類不兼容。你需要一個第三方庫來處理它們,比如[NodaTime](https://code.google.com/p/noda-time/) – 2013-03-02 19:05:10

+0

,謝謝Matt。我最終不得不使用Nodatime來使用Olson時間格式,但同意你的觀點,即映射回Windows時區名稱是容易出錯的。很多SOF的問題與大型詞典的答案一樣。此頁面似乎是我找到的最佳數據源:http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/zone_tzid.html – leora 2013-03-05 05:53:21

回答

5

不知道這樣的內置到C#,但你可以使用,谷歌地圖API什麼:

1)獲取長期/緯度的城市:http://maps.googleapis.com/maps/api/geocode/json?address=New%20York,%20CA&sensor=false

2)現在使用的長/ LAT獲得時區:https://maps.googleapis.com/maps/api/timezone/json?location=43.2994285,-74.21793260000001&timestamp=1362209227&sensor=false

示例代碼:

public TimeZoneResponse ConvertCityToTimeZoneName(string location) 
    { 
     TimeZoneResponse response = new TimeZoneResponse(); 
     var plusName = location.Replace(" ", "+"); 
     var address = "http://maps.google.com/maps/api/geocode/json?address=" + plusName + "&sensor=false"; 
     var result = new System.Net.WebClient().DownloadString(address); 
     var latLongResult = JsonConvert.DeserializeObject<GoogleGeoCodeResponse>(result); 

     if (latLongResult.status == "OK") 
     { 
      var timeZoneRespontimeZoneRequest = "https://maps.googleapis.com/maps/api/timezone/json?location=" + latLongResult.results[0].geometry.location.lat + "," + latLongResult.results[0].geometry.location.lng + "&timestamp=1362209227&sensor=false"; 
      var timeZoneResponseString = new System.Net.WebClient().DownloadString(timeZoneRespontimeZoneRequest); 
      var timeZoneResult = JsonConvert.DeserializeObject<TimeZoneResult>(timeZoneResponseString); 

      if (timeZoneResult.status == "OK") 
      { 

       response.TimeZoneName = timeZoneResult.timeZoneName; 
       response.Success = true; 
       return response; 
      } 
     } 
     return response; 
    } 
+1

我已將工作代碼添加到答案中,但要澄清上面的代碼給了我奧爾森時間。我仍然需要使用另一個映射將Olson時間轉換爲Windows時區 – leora 2013-03-05 05:52:12

2

您可以使用根據知識共享署名3.0許可證提供的免費時區數據庫。你可以在這裏找到關於它的信息:

http://timezonedb.com/

您可以使用SQL維持原樣,或者你可以在SQL數據庫到應用程序中的某些類拔...

2

EarthTools.org有一個免費的Web服務,您可以通過經/緯像查詢:

http://www.earthtools.org/timezone/<latitude>/<longitude> 

例紐約:

http://www.earthtools.org/timezone-1.1/40.71417/-74.00639 

但是不,我不知道有這樣做的任何烘焙類。

0

您可以在.NET框架中得到的最接近的是TimeZonInfo.GetSys temTimeZones()。

請注意,在您的案例中不存在一對一映射,例如,悉尼,澳大利亞一個,加拿大另一個。