我有一种情况,其中日期为"3/13/2016 2:41:00 AM"
。当我按时区转换日期时,我收到错误。
DateTime dt = DateTime.Parse("3/13/2016 2:41:00 AM");
DateTime Date_Time = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, "Eastern Standard Time",
"GMT Standard Time");
Response.Write(dt);
执行后,我收到此错误:
提供的DateTime表示无效时间。例如,何时 在跳过的时间段内的任何时间向前调整时钟 是无效的。参数名称:dateTime
答案 0 :(得分:11)
尝试检查时间是否模糊或有效时间。 Due to the daylight change你提到的时间,即凌晨2:41:00不存在,因为时钟提前1小时移动,因此日期无效或含糊不清。
2016 Sun, 13 Mar, 02:00 CST → CDT +1 hour (DST start) UTC-5h
Sun, 6 Nov, 02:00 CDT → CST -1 hour (DST end) UTC-6h
您也可以参考此博客:System.TimeZoneInfo: Working with Ambiguous and Invalid Points in Time
System.TimeZoneInfo(目前作为.NET Framework 3.5的一部分提供 Beta 1)包含检查DateTime实例的方法 表示特定时区中的模糊或无效时间。这些 方法对于验证用户提供的点特别有用 时间。
背景资料
调整夏令时间的时区(大多数情况下) 将时钟时间向前或向后移动1小时的情况有间隙 并在时间线中重复 - 时钟时间移动的地方 通过调整前进或后退。我们用太平洋标准时间作为 一个例子。 2007年太平洋标准时间(PST)改为太平洋地区 第二个星期天上午02:00(“春季前进”)的夏令时(PDT) 在三月,然后在第一个星期天凌晨02:00(“退回”)返回 十一月
要检查时间是否有效,您可以使用:
TimeZoneInfo.IsInvalidTime
答案 1 :(得分:0)
在我的情况下,我试图转换UTC日期(因此,这是有效的,因为UTC日期不会使用DST跳过任何时间段)。
问题是我正在从Entity Framework中加载日期,并且DateKind
设置为Unspecified
。在这种情况下,ConvertTimeBySystemTimeZoneId
假设它是当地时间,可能会发现它无效。
解决方案是在转换之前将DateKind
设置为UTC
:
var date = DateTime.ParseExact("2019-03-31T03:06:55.7856471", "O", CultureInfo.InvariantCulture);
// Here date.Kind == DateTimeKind.Unspecified
date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
// Now date.Kind == DateTimeKind.Utc
// Now the conversion should work
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(date, "Central Standard Time");