2008-10-22 46 views
2

我無法理解系統註冊表如何幫助我將DateTime對象轉換爲相應的TimeZone。我有一個例子,我一直在嘗試進行逆向工程,但我不能遵循UTC時間根據夏令時偏移的一個關鍵步驟。在WPF/C#中顯示時區。發現夏令時間偏移

我使用.NET 3.5(感謝上帝),但它仍然讓我感到莫名其妙。

感謝

編輯:附加信息:這個問題是在一個WPF應用程序環境中使用。我留下的代碼片段使答案更進一步,以獲得我正在尋找的內容。

+1

只是想我應該指出,這與WPF無關,所以你可能想從標題/描述/標籤中刪除。 – PeterAllenWebb 2008-10-22 18:46:25

+0

其實,我的問題是用於WPF應用程序,正如你可以通過我的答案看到的。雖然它是.NET代碼,但WPF是最終用途,所以我下面留下的代碼片段是C#for WPF。 – discorax 2008-10-22 19:16:55

回答

9

這是我在我的WPF應用程序中使用的C#代碼片段。這會爲您提供您提供的時區ID的當前時間(根據夏令時調整)。

// _timeZoneId is the String value found in the System Registry. 
// You can look up the list of TimeZones on your system using this: 
// ReadOnlyCollection<TimeZoneInfo> current = TimeZoneInfo.GetSystemTimeZones(); 
// As long as your _timeZoneId string is in the registry 
// the _now DateTime object will contain 
// the current time (adjusted for Daylight Savings Time) for that Time Zone. 
string _timeZoneId = "Pacific Standard Time"; 
DateTime startTime = DateTime.UtcNow; 
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId); 
_now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst); 

這是我結束的代碼snippit。謝謝您的幫助。

3

您可以使用DateTimeOffset獲取UTC偏移量,因此您不需要深入該註冊表以獲取該信息。

TimeZone.CurrentTimeZone返回額外的時區數據,TimeZoneInfo.Local具有關於時區的元數據(例如是否支持夏令時,各種狀態的名稱等)。

更新:我認爲這明確回答你的問題:

var tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); 
var dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset); 
Console.WriteLine(dto); 
Console.ReadLine(); 

這代碼創建一個DateTime -8偏移。默認安裝時區爲listed on MSDN

0
//C#.NET 
    public static bool IsDaylightSavingTime() 
    { 
     return IsDaylightSavingTime(DateTime.Now); 
    } 
    public static bool IsDaylightSavingTime(DateTime timeToCheck) 
    { 
     bool isDST = false; 
     System.Globalization.DaylightTime changes 
      = TimeZone.CurrentTimeZone.GetDaylightChanges(timeToCheck.Year); 
     if (timeToCheck >= changes.Start && timeToCheck <= changes.End) 
     { 
      isDST = true; 
     } 
     return isDST; 
    } 


'' VB.NET 
Const noDate As Date = #1/1/1950# 
Public Shared Function IsDaylightSavingTime(_ 
Optional ByVal timeToCheck As Date = noDate) As Boolean 
    Dim isDST As Boolean = False 
    If timeToCheck = noDate Then timeToCheck = Date.Now 
    Dim changes As DaylightTime = TimeZone.CurrentTimeZone _ 
     .GetDaylightChanges(timeToCheck.Year) 
    If timeToCheck >= changes.Start And timeToCheck <= changes.End Then 
     isDST = True 
    End If 
    Return isDST 
End Function