3

我无法理解系统注册表如何帮助我将 DateTime 对象转换为相应的 TimeZone。我有一个示例,我一直在尝试进行逆向工程,但我无法遵循 UTCtime 根据夏令时偏移的关键步骤。

我正在使用 .NET 3.5(感谢上帝),但它仍然让我感到困惑。

谢谢

编辑:附加信息:此问题用于 WPF 应用程序环境。我在下面留下的代码片段使答案示例更进一步,以获得我正在寻找的内容。

4

3 回答 3

10

这是我在 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);

这是我最终得到的代码片段。谢谢您的帮助。

于 2008-10-22T18:44:40.843 回答
4

您可以使用 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();

该代码在 -8 偏移处创建一个 DateTime。MSDN 上列出了默认安装的时区。

于 2008-10-22T15:52:15.480 回答
1
//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
于 2011-03-10T23:21:27.890 回答