AlGoreRhythm AlGoreRhythm - 8 days ago 14
C# Question

Is there a way to convert this kind of string into a date?

Trying to convert a string like this

Dec 1, 2016 1:48 PM CST
into a DateTime object.

Convert.ToDateTime(story.AddedDateString);
Didn't work, nor did I really expect it to.


System.FormatException: The string was not recognized as a valid
DateTime. There is an unknown word starting at index 21.


is the error message I get. Wondering if I can tell it the format before trying to convert?

Answer

DateTime.ParseExact will get you most of the way there. For example:

string input = "Dec 1, 2016  1:48 PM";
DateTime date = DateTime.ParseExact(input, "MMM d, yyyy  h:mm tt", CultureInfo.InvariantCulture);

However, it does not handle the time zone via an abbreviation, as there are multiple time zones with CST as an abbreviation. Conversion of "CST" to an offset is not supported directly within the framework.

If you convert to a format which includes the offset, you can convert it:

string input = "Dec 1, 2016  1:48 PM -06:00";
DateTime date = DateTime.ParseExact(input, "MMM d, yyyy  h:mm tt K", CultureInfo.InvariantCulture);