C# parsing to datetime regardless of culture info

£可爱£侵袭症+ 提交于 2019-12-12 03:52:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!