Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better DateTime.Parse out there? [closed]

Tags:

c#

.net

datetime

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.

like image 822
Mike Gates Avatar asked Feb 18 '26 22:02

Mike Gates


2 Answers

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);
like image 98
SLaks Avatar answered Feb 20 '26 11:02

SLaks


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 :( ).

like image 28
Jeff Sternal Avatar answered Feb 20 '26 11:02

Jeff Sternal