简体   繁体   English

ASP.NET Convert.ToDateTime(“ Tue,08 Sep 2009 13:31:00 -0500”)关闭一个小时

[英]ASP.NET Convert.ToDateTime(“Tue, 08 Sep 2009 13:31:00 -0500”) is off by an hour

Using the ASP.NET 3.5 framework, Convert.ToDateTime("Tue, 08 Sep 2009 13:31:00 -0500") returns a DateTime object with a time of 14:31. 使用ASP.NET 3.5框架,Convert.ToDateTime(“ Tue,08 Sep 2009 13:31:00 -0500”)返回时间为14:31的DateTime对象。 Note that I'm on the East Coast (EST -0500) so I should be seeing 13:31. 请注意,我在东海岸(EST -0500),所以我应该看到13:31。 I'm assuming this has to do with Daylight Saving Time (DST) not being accounted for in Convert.ToDateTime. 我假设这与在Convert.ToDateTime中未考虑的夏令时(DST)有关。

Is there an elegant way to correct this problem that would work across all time zones? 有没有一种优雅的方法可以解决在所有时区都可以解决的问题?

Is there a different date parsing method I should be aware of that would avoid this issue? 我应该知道是否有其他日期解析方法可以避免此问题?

Use the DateTimeOffset structure instead: 请改用DateTimeOffset结构

DateTimeOffset.Parse("Tue, 08 Sep 2009 13:31:00 -0500")

It also has a constructor that takes a TimeSpan structure . 它还具有采用TimeSpan结构 的构造函数 This should respect the DST issue. 这应该尊重DST问题。

Since you mentioned timezones, another class to look into is the TimeZoneInfo class . 由于您提到了时区,因此需要研究的另一个类是TimeZoneInfo类 These are both new in .NET 3.5. 这些都是.NET 3.5中的新功能。 The example from this MSDN page returns: MSDN页面上的示例返回:

Time in Eastern Daylight Time zone: 9/8/2009 3:25:58 PM
    UTC Time: 9/8/2009 7:25:58 PM
Time in Tokyo Daylight Time zone: 9/9/2009 4:25:58 AM
    UTC Time: 9/8/2009 7:25:58 PM

If you are on the east coast, and since it is currently Daylight Saving Time on the east coast, your time should be Tue, 08 Sep 2009 13:31:00 -0400 . 如果您位于东海岸,并且由于目前是东海岸的夏令时,您的时间应该为Tue, 08 Sep 2009 13:31:00 -0400 During daylight saving time, the offset on the east coast become -04:00 . 在夏时制期间,东海岸的偏移量变为-04:00

A quick way to check your current offset is 快速检查当前偏移量的方法是

TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);

So you are actually parsing a wrong value. 因此,您实际上是在解析错误的值。 It is impossible for a date on the east coast to be at -05:00 on September 8. 东海岸的日期不可能是9月8日的-05:00。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM