How to convert datetime string in format MMMdyyyyhhmmtt to datetime object?

Alexei’s answer is quite right, I wanna explain little bit deep if you let me..

You are thinking 5 should match with d specifier, right? But this is not how DateTime.ParseExact works under the hood.

Since The "d" custom format specifier represents number from 1 through 31, this specifier will map 52 in your string, not just 5. That’s why your code throws FormatException.

As you can see, your string format can’t parsed unless you do it some string manipulations with it.

In such a case, .NET Team suggests either using two digit forms like 05 or insert separators for your date and time values.

You can create a custom method that parse this MMMdyyyyhhmmtt format for only parse this kind of formatted strings like;

public static DateTime? ParseDate_MMMdyyyyhhmmtt(string date)
{
    if (date == null)
        return null;
    if (date.Length < 14)
        return null;
    if (date.Length == 14)
        date = date.Insert(3, "0");
    DateTime dt;
    if (DateTime.TryParseExact(date, "MMMdyyyyhhmmtt",
                               CultureInfo.InvariantCulture,
                               DateTimeStyles.None, out dt))
        return dt;
    return null;
}

Leave a Comment