c# – DateTime解析错误:提供的DateTime表示无效时间

前端之家收集整理的这篇文章主要介绍了c# – DateTime解析错误:提供的DateTime表示无效时间前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一种情况,日期是“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);

执行后,我收到此错误

The supplied DateTime represents an invalid time. For example,when@H_301_8@ the clock is adjusted forward,any time in the period that is skipped@H_301_8@ is invalid. Parameter name: dateTime

解决方法

尝试检查时间是否模糊或有效时间. Due to the daylight change你提到的时间,即2:41:00 AM不存在,因为时钟提前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 (currently available as part of .NET Framework 3.5@H_301_8@ Beta 1) contains methods for checking if a DateTime instance@H_301_8@ represents an ambiguous or invalid time in a specific time zone. These@H_301_8@ methods are particularly useful for validating user-supplied points in@H_301_8@ time.

Background Information

Time zones that adjust their time for Daylight Saving Time (in most@H_301_8@ cases by moving the clock time back or forward by 1 hour) have gaps@H_301_8@ and repeats in the timeline — wherever the clock time was moved@H_301_8@ forward or back by the adjustment. Let’s use Pacific Standard Time as@H_301_8@ an example. In 2007 Pacific Standard Time (PST) changes to Pacific@H_301_8@ Daylight Time (PDT) at 02:00AM (“spring forward”) on the second Sunday@H_301_8@ in March and then returns at 02:00AM (“fall back”) on the first Sunday@H_301_8@ in November

要检查时间是否有效,您可以使用:

TimeZoneInfo.IsInvalidTime

猜你在找的C#相关文章