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

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

由于

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

有帮助吗?

解决方案

以下是我在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。谢谢你的帮助。

其他提示

您可以使用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上列出

//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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top