简体   繁体   中英

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. Note that I'm on the East Coast (EST -0500) so I should be seeing 13:31. I'm assuming this has to do with Daylight Saving Time (DST) not being accounted for in Convert.ToDateTime.

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.Parse("Tue, 08 Sep 2009 13:31:00 -0500")

It also has a constructor that takes a TimeSpan structure . This should respect the DST issue.

Since you mentioned timezones, another class to look into is the TimeZoneInfo class . These are both new in .NET 3.5. The example from this MSDN page returns:

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 . During daylight saving time, the offset on the east coast become -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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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