pcoonan pcoonan - 2 months ago 13
C# Question

DateTime string conversion with both month name and AM/PM

I've looked at a bunch of questions regarding parsing strings into a DateTime object, but none seem to have the same format as I do. The strings that I need to parse into a DateTime object are in this format:


Jun 29 2016 12:57PM

Jan 1 1900 12:00AM


The format I am trying is the following:

DateTime.ParseExact(date, "MMM dd yyyy hh:mmtt", CultureInfo.InvariantCulture)


but this throws a FormatException. Any suggestions?

Answer

You might want to look over the Custom Date and Time Format Strings page on MSDN. I think your issue is that your current format is requiring leading zeros on both your day and hour. For example, this would look like

Jan 01 1900 01:00PM

You are probably wanting to use the format

DateTime.ParseExact(date, "MMM d yyyy h:mmtt", null)

which does not require the leading zeros for the day and hour positions. This would match values such as

Jan 1 1900 1:00PM

I hope this helps.