15
votes

I have a string s = "May 16, 2010 7:20:12 AM CDT that i want to convert into a DateTime object. In the code below i get a Date format cannot be converted error when attempting to parse the text with a known format.

timeStamp = matches[0].Groups[1].Value;
dt = DateTime.ParseExact(timeStamp, "MMM dd, yyyy H:mm:ss tt", null);

The timezone comes in as CDT UTC... and i think is whats causing the problem or my format?

2
How about var dt = DateTime.ParseExact(s, "MMM dd, yyyy H:mm:ss tt 'CDT'", null); ?Vlad

2 Answers

10
votes

Central Daylight Time

Try this:

string dts = "May 16, 2010 7:20:12 AM CDT";
DateTime dt = 
    DateTime.ParseExact(dts.Replace("CDT", "-05:00"), "MMM dd, yyyy H:mm:ss tt zzz", null);

EDIT:

For daylight savings time please consider DateTime.IsDaylightSavingTime and TimeZone.CurrentTimeZone

Custom Date and Time Format Strings

8
votes

Make sure the DateTime is unambiguously DateTimeKind.Utc. Avoid "GMT", it is ambiguous for daylight saving.

    var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);
    string s = dt.ToLocalTime().ToString("MMM dd, yyyy HH:mm:ss tt \"GMT\"zzz");

it's gives output : Dec 31, 2010 19:01:01 pm GMT-06:00

For more detail refer this Link