Does anyone know of a library (paid or not) out there that is able to handle more common datetime formats than DateTime.Parse uses? Something that can handle multiple languages and abbreviations for days/months would be really nice.
For example: "Sept 1, 2009" does not work with Datetime.Parse.
To parse dates with non-standard abbreviations, you'll need to create your own culture.
For example: (Tested)
var culture = new CultureInfo("en-US");
culture.DateTimeFormat.AbbreviatedMonthNames = new string[] {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec", ""
};
DateTime.Parse("Sept 1, 2009", culture);
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 :( ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With