I've used code like the following in the past (where the expectedDateTimeFormats
are strings that follow the rules for Custom Date and Time Format Strings):
// 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's 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're dealing with non-standard abbreviations (like "Sept 1, 2009" as you mentioned in a comment), you may have to create a custom CultureInfo
or DateTimeFormatInfo
and define them yourself.
I don't know of a really good list of 'standard' custom formats (and/or related DateTimeFormatInfo
definitions) - if anyone can find one they certainly deserve to be the accepted answer. I no longer have access to one my old team used (and wouldn't have had permission to share it anyway :( ).