Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string into date using C# in ASP.NET gets me a date an hour off. Why?

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?

like image 498
ahmd0 Avatar asked Dec 22 '22 00:12

ahmd0


2 Answers

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 call DateTimeOffset.Parse and then retrieve the DateTime component of the result:

DateTime dt = DateTimeOffset.Parse("2012-03-11T02:53:58-08:00").DateTime;
string strDt = dt.ToString();  // "3/11/2012 2:53:58 AM"

UPDATE: So what's the difference between DateTime.Parse and DateTimeOffset.Parse when the original string contains a time zone offset? Consider these two examples, which assume your current time zone is Pacific Time:

// Example 1: DateTime.Parse(String)
DateTime dt = DateTime.Parse("2012-03-11T06:00:00-04:00");
Console.WriteLine(dt.ToString("o"));  // 2012-03-11T03:00:00.0000000-07:00

DateTime.Parse uses 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 because DateTime.Parse automatically adjusted the time from Pacific Standard Time (UTC-08:00) to Pacific Daylight Time (UTC-07:00).

// Example 2: DateTimeOffset.Parse(String)
DateTimeOffset dto = DateTimeOffset.Parse("2012-03-11T06:00:00-04:00");
Console.WriteLine(dto.DateTime.ToString("o"));  // 2012-03-11T06:00:00.0000000
Console.WriteLine(dto.Offset);                  // -04:00:00

DateTimeOffset.Parse is simpler. It just returns a DateTimeOffset value whose DateTime and Offset properties 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.

like image 82
Michael Liu Avatar answered Feb 22 '23 22:02

Michael Liu


It's allowing for the Time Zone you are in. The time string is in ISO8601 format with timezone.

http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

like image 37
Steve Wellens Avatar answered Feb 22 '23 22:02

Steve Wellens