I’m coding the following using VS2010, C#, ASP.NET:
DateTime dt = DateTime.Parse("2012-03-11T02:53:58-08:00"); //Date is taken from SQL database
string strDt = dt.ToString(); //Becomes: "3/11/2012 3:53:58 AM"
Is this April’s fools joke from Microsoft?
The “incorrect” result (as darkmyst’s answer explains) is caused by the fact that March 11, 2012, 2:38:58 AM, was not a valid date and time in areas of the United States and Canada that observe daylight saving time. Evidently, your code is running on a computer in one of these areas.
To convert a string to a
DateTime, ignoring any time zone offset, you can callDateTimeOffset.Parseand then retrieve theDateTimecomponent of the result:UPDATE: So what’s the difference between
DateTime.ParseandDateTimeOffset.Parsewhen the original string contains a time zone offset? Consider these two examples, which assume your current time zone is Pacific Time:DateTime.Parseuses the offset to adjust the parsed date and time to local time. Note that the time has changed from 6 AM to 3 AM, reflecting the conversion from Eastern Daylight Time (UTC-04:00) to Pacific Daylight Time (UTC-07:00). In your question, the time changed becauseDateTime.Parseautomatically adjusted the time from Pacific Standard Time (UTC-08:00) to Pacific Daylight Time (UTC-07:00).DateTimeOffset.Parseis simpler. It just returns aDateTimeOffsetvalue whoseDateTimeandOffsetproperties are set to the parsed date, time, and offset. But beware: If the time zone offset in the string doesn’t match the time zone you want to work with, then you need to adjust the resulting date and time yourself.