Unable to convert custom string format to DateTime

I’m trying to convert a custom string into a DateTime. I’ve seen several blogs and forum threads use this technique to manage a custom format.

            string mysqlDateFormat = "yyyy-M-dd hh:mm:ss"; // MySQL Date Format expressed in C# custom date format specifiers (e.g. 2011-6-07 06:18:14)
            DateTime inputTestCompletedDateTime = new DateTime();
            if (!DateTime.TryParse(inputTestCompletedDateTimeAsString, out inputTestCompletedDateTime))
            {                
                inputTestCompletedDateTime = DateTime.ParseExact(inputTestCompletedDateTimeAsString, mysqlDateFormat, System.Globalization.CultureInfo.InvariantCulture);
            }

However, this code throws an error on the line within the if statement, " Exception Details: System.FormatException: The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.".

I’ve attempted modifications but they’ve all been less successful (where the string is not recognized as valid). However, I thought using the “CultureInfo.InvariantCulture” was the secret to processing custom (i.e. non-Gregorian) formatting.

Shouldn’t the month have a leading 0? i.e. “06” instead of “6”

It doesn’t look like it. The format in Workbench and when I just dump the DB table to a DataTable and render it in XHTML is 0000-0-00 00:00:00. I don’t know why they render all elements in two digits except for month but they do. However, if I try formatting with pattern yyyy-MM… it fails with the error,
" Exception Details: System.FormatException: String was not recognized as a valid DateTime."

As a modification (which I do like a little better) I rewrote the DAL code to convert the month to fixed two digits, %Y-%m…, it needs a DATE_FORMAT call anyway. This hasn’t fixed the problem, but I am at least back to the GregorianCalendar error. I think that’s closer to a solution.

I still don’t understand why it expects the string to be compatible with GregorianCalendar. All the examples I’ve seen allow you to specify InvariantCulture and write crazy custom string patterns. Certainly much more twisted stuff than the year-month-date hour:minutes:seconds which I’m using.

Convert.ToDateTime(Your custom string) this might helps you.