.NET 的文档 DateTime.ToLocalTime方法指出:
On Windows XP systems, the ToLocalTime method recognizes only the current adjustment rule when converting from UTC to local time. As a result, conversions for periods before the current adjustment rule came into effect may not accurately reflect the difference between UTC and local time.
我正在 Windows 7 上开发,但部署到混合环境。如何提供与 ToLocalTime 的 Windows 7 行为相匹配的一致、正确的实现?
编辑
我进行了一个测试:
static void Main()
{
// 8 AM in July, UTC. That would have been DST, so 3 AM CDT.
var dstDate = new DateTime(2010, 7, 1, 8, 0, 0, DateTimeKind.Utc);
// 8 AM in December, UTC. Not DST, so 2 AM CST.
var nonDstDate = new DateTime(2010, 12, 1, 8, 0, 0, DateTimeKind.Utc);
Log("DST Date ToLocalTime: " + dstDate.ToLocalTime());
Log("DST Date ConvertTimeFromUtc: " + ConvertTimeFromUtc(dstDate));
Log("Expected: 3 AM July 1 2010");
Log(string.Empty);
Log("Non-DST Date ToLocalTime: " + nonDstDate.ToLocalTime());
Log("Non-DST Date ConvertTimeFromUtc: " + ConvertTimeFromUtc(nonDstDate));
Log("Expected: 2 AM December 1 2010");
Log(string.Empty);
Log("Date ToLocalTime Kind: " + dstDate.ToLocalTime().Kind);
Log("Date ConvertTimeFromUtc Kind: " + ConvertTimeFromUtc(dstDate).Kind);
}
private static void Log(string message)
{
Console.WriteLine(message);
}
private static DateTime ConvertTimeFromUtc(DateTime utcDateTime)
{
return
DateTime.SpecifyKind(
TimeZoneInfo.ConvertTimeFromUtc(
utcDateTime,
TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id)),
DateTimeKind.Local);
}
结果是相同 在 XP Pro 32 位、SP3(作为 VM)和 Windows 7 Enterprise 64 位下:
DST 日期至本地时间:2010 年 7 月 1 日凌晨 3:00:00
DST 日期 ConvertTimeFromUtc:2010 年 7 月 1 日凌晨 3:00:00
预计:2010 年 7 月 1 日凌晨 3 点
非 DST 日期 ToLocalTime:12/1/2010 2:00:00 AM
非夏令时日期 ConvertTimeFromUtc:12/1/2010 2:00:00 AM
预计:2010 年 12 月 1 日凌晨 2 点
日期到本地时间种类:本地
日期 ConvertTimeFromUtc 种类:本地
文档有错吗?我可以简单地调用 ToLocalTime 吗?
编辑 2
我们在实际的 XP 系统(不是虚拟机)上运行它,并在那里得到了相同的结果。我的测试用例是否正确?谁能提供一个结果会有所不同的案例?
最佳答案
On Windows XP systems, the ToLocalTime method recognizes only the current adjustment rule when converting from UTC to local time. As a result, conversions for periods before the current adjustment rule came into effect may not accurately reflect the difference between UTC and local time.
美国在 2007 年更改了夏令时的调整规则。
错误是他们对所有日期都遵循 2007 年规则,而不仅仅是 2007 年之后的日期。DST 规则在 20 年中没有改变,Windows XP 只是没有不同年份不同规则的概念。它会将 2006 年 10 月 31 日视为夏令时,而实际上并非如此。
如果你只处理 2007 年之后的日期,那么你很好,不需要做任何特别的事情。如果您要处理 2006 年或之前的日期,则需要检查年份,并手动应用 DST 偏移量。
关于.net - Windows XP 上的 DateTime.ToLocalTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4960303/