1

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?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
jdmdevdotnet
  • 1
  • 2
  • 19
  • 50
  • 4
    Consider searching for keywords like **parse**. Because that sounds like what you're trying to do. Parse a string into a DateTime object, and provide a custom format. – Sunny Patel Dec 01 '16 at 20:08

2 Answers2

9

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);
Community
  • 1
  • 1
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

You can use DateTime.ParseExact() and specify a format string using the DateTime formatters available.

As an example:

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

The only problem with this is that it won't handle your timezone. You'd have to handle the timezone by either replacing that portion of the string with a UTC offset (which DateTime.ParseExact() WILL handle if you use the format zzz which looks like -06:00) or removing that portion of the string and accounting for the timezone after you have an actual date object.

You can read more at https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx

Ryan Griffith
  • 1,591
  • 17
  • 41