2014-02-22 143 views
5

如果我們提供時區的名稱,如"America/Phoenix",有什麼方法可以在C#中獲取當前日期和時間?如何從TimeZone Name中獲取日期和時間

我曾嘗試下面的代碼: -

TimeZoneInfo ZoneName = System.TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time"); 
DateTime dataTimeByZoneId = System.TimeZoneInfo.ConvertTime(DateTime.Now,System.TimeZoneInfo.Local, ZoneName); 

,但它需要/預期的輸入作爲"US Standard Time Zone"。 我希望輸入爲"America/Phoenix"。如果我們在C#中有任何選項/方法來實現這一點,請告訴我們嗎?

+1

處理時間和日期相關的任務,我會建議使用野田的時間。有關更多信息,請參閱http://nodatime.org/。 – Ikaso

+0

看看這個[** link **](http://stackoverflow.com/questions/17974633/get-timezone-offset-of-server-in-c-sharp)。它可能會幫助你:) – Rohit416

回答

-1

創建您的具體timezone,然後使用:

DateTime local = zone.ToLocalTime(DateTime.Now); 
1

時區ID的喜歡America/Phoenix來自IANA time zone database。 .Net的TimeZoneInfo類不使用該數據。詳細信息請參見the timezone tag wiki

要在.NET中使用IANA時區標識符,您應該查看Noda Time。這裏是你用野田時間如何獲取當前本地時間America/Phoenix

Instant now = SystemClock.Instance.Now; 
DateTimeZone tz = DateTimeZoneProviders.Tzdb["America/Phoenix"]; 
ZonedDateTime zdt = now.InZone(tz); 

// Then depending on what your needs are, pick one of the following: 
LocalDateTime ldt = zdt.LocalDateTime; 
DateTime dt = zdt.ToDateTimeUnspecified(); 
DateTimeOffset dto = zdt.ToDateTimeOffset(); 
+0

感謝您的迴應。執行代碼後會讓你知道 – Neharika

相關問題