Better DateTime.Parse there?

Does anyone know of a library (paid or not) that can handle more common datetime formats than DateTime.Parse? Something that can handle multiple languages ​​and abbreviations for days / months would be very nice.

For example: "September 1, 2009" does not work with Datetime.Parse.

+4
source share
6 answers

To analyze dates with custom abbreviations, you need to create your own culture.

For example: (verified)

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); 
0
source

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

+4
source

I should also point out that there are DateTime.TryParse and DateTIme.TryParseExact . I think it's incredibly rude that you need to worry about exceptions from trying to convert a string to DateTime or <insert object type here> .

+2
source

To handle multiple languages, you can call DateTime.Parse with different cultures.

DateTime.Parse will handle abbreviations out of the box.

If you need to handle custom combinations, call DateTime.ParseExact .

+1
source

I can not answer your question. Consider DateTime.ParseExact if you don't get the answer you like.

+1
source

I don’t know if he has the “best” parsers, but you can check the OS Skeet project , Noda Time

0
source

Source: https://habr.com/ru/post/1301136/


All Articles