问题
I have problem parsing some date string where language is not english. The sample date string is "8 avril 2016 vendredi" which is "8 april 2016 friday" in english.
I have tried this but no luck.
DateTime dateTime;
DateTime.TryParse("8 avril 2016 vendredi", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
In my case, date string can be in any language so I cannot specify the culture in parsing.
I appreciate your help. Thanks.
回答1:
Behold, the terrible any parser!
CultureInfo.GetCultures(CultureTypes.AllCultures).Select(culture => {
DateTime result;
return DateTime.TryParse(
"8 avril 2016 vendredi",
culture,
DateTimeStyles.None,
out result
) ? result : default(DateTime?);
})
.Where(d => d != null)
.GroupBy(d => d)
.OrderByDescending(g => g.Count())
.FirstOrDefault()
.Key
This asks every culture on the system to parse the date, and picks the date that emerges most frequently as the "winner". It returns null
if no culture could parse the date.
It isn't hard to think of ways this can fail to provide the correct result, because the most common result isn't necessarily the correct one and some dates are truly ambiguous. Is "04-05-2016" the fourth of May or the fifth of April? The any parser thinks the fourth of May is more likely simply because more cultures parse it that way. On my machine, at least. But that will not please American authors (who are overrepresented on the Internet), so maybe the probability of cultures needs to be taken into account.
This code should not be used to parse arbitrary user input, let alone all input, and even in the context of a scraper that truly lacks all other clues about the language, this is probably not the best approach. Also beware that this is slow; there are hundreds of cultures on an average machine. Guessing the whole culture for a page first and then consistently parsing based on that is absolutely a better idea.
来源:https://stackoverflow.com/questions/40892469/c-sharp-parsing-to-datetime-regardless-of-culture-info