In the past, I used code similar to the one below (where expectedDateTimeFormats are strings that follow the rules for Custom strings in date and time format ):
// Or use custom DateTimeFormatInfo objects string[] expectedDateTimeFormats = new string[] { "customFormat1", "customFormat2", "customFormatN", }; // You could offer several overloads here, to accept other DateTimeStyles, // InvariantCulture, CurrentUICulture, etc. - perhaps even a collection of // CultureInfo objects to try public DateTime TryParseDateString(string dateString, CultureInfo culture) { try { // first, try to parse given the specified culture formats return DateTime.Parse(dateString, culture); } catch (FormatException) { // if that fails, try your custom formats return DateTime.ParseExact(dateString, expectedDateTimeFormats, culture, DateTimeStyles.None); } }
If you are dealing with non-standard abbreviations (for example, “September 1, 2009,” as you mentioned in the comment), you may need to create a custom CultureInfo or DateTimeFormatInfo and define them yourself.
I don’t know a really good list of “standard” user formats (and / or related DateTimeFormatInfo definitions) - if someone can find one that certainly deserves to be accepted. I no longer have access to one of my old commands (and I would not have permission to share it :().
source share