There is no way to parse your string without changing it because M
format specifier can be two digits and it will map to parse 51
as a month. That's why your operation throws FormatException
. Same with h
format specifier.
That's why we need to change your string from 515201483742AM
to 05152014083742AM
to provide M
format specifier will map 05
and h
format specifier will map 08
.
You can use a method like1;
public static DateTime? ParseDate_Mdyyyyhmmsstt(string date)
{
if (date == null)
return null;
if (date.Length < 14)
return null;
if (date.Length == 14)
date = date.Insert(0, "0").Insert(8, "0");
DateTime dt;
if (DateTime.TryParseExact(date, "Mdyyyyhmmsstt",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
return dt;
return null;
}
And call it like;
var dt = ParseDate_Mdyyyyhmmsstt("515201483742AM");
Console.WriteLine(dt.Value); // 15.05.2014 08:37:42
1: I know this is not an elegant solution but it works in your case when your month and hour part is 1 digit.
Read: DateTime conversion from string C#