我无法理解系统注册表如何帮助我将DateTime对象转换为相应的TimeZone。我有一个例子,我一直在尝试进行逆向工程,但我不能遵循UTC时间根据夏令时偏移的一个关键步骤。在WPF/C#中显示时区。发现夏令时间偏移
我使用.NET 3.5(感谢上帝),但它仍然让我感到莫名其妙。
感谢
编辑:附加信息:这个问题是在一个WPF应用程序环境中使用。我留下的代码片段使答案更进一步,以获得我正在寻找的内容。
我无法理解系统注册表如何帮助我将DateTime对象转换为相应的TimeZone。我有一个例子,我一直在尝试进行逆向工程,但我不能遵循UTC时间根据夏令时偏移的一个关键步骤。在WPF/C#中显示时区。发现夏令时间偏移
我使用.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();
这代码创建一个DateTime -8偏移。默认安装时区为listed on 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
只是想我应该指出,这与WPF无关,所以你可能想从标题/描述/标签中删除。 – PeterAllenWebb 2008-10-22 18:46:25
其实,我的问题是用于WPF应用程序,正如你可以通过我的答案看到的。虽然它是.NET代码,但WPF是最终用途,所以我下面留下的代码片段是C#for WPF。 – discorax 2008-10-22 19:16:55