DateTime.TryParse different results

孤街浪徒 提交于 2020-01-15 12:28:06

问题


As part of my unittests for an application I check a few datetime strings for their ability to get parsed. I recently noticed that on one machine the string "0-02-20 11:36" can get parsed to {2000-02-20 11:36:00} by DateTime.TryParse(dateString, out parsedTimeStamp) while on other machines it can't.

string dt = "0-02-20 11:36";
DateTime parsedTimeStamp;
DateTime.TryParse(dateString, out parsedTimeStamp);
Console.WriteLine(parsedTimeStamp);

回答1:


Parsing a DateTime, like all parsing in the framework, is culture dependent.

I would assume that on the exceptional machine, the culture settings use a yyyy-MM-dd format, while on the other machines, the date format was MM-dd-yyyy.

To work around this, you can parse in a specific culture or using an invariant culture.

DateTime.TryParse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedTimeStamp);

It turns out there are quite a few of these cultures:

foreach (var c in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
    if (c.DateTimeFormat.ShortDatePattern == "yyyy-MM-dd")
    {
        Console.WriteLine("{0}: {1}", c.DisplayName, c.DateTimeFormat.ShortDatePattern);
    }
}

Korean: yyyy-MM-dd  
Polish: yyyy-MM-dd  
Albanian: yyyy-MM-dd  
Swedish: yyyy-MM-dd  
Khmer: yyyy-MM-dd  
Sinhala: yyyy-MM-dd  
Korean (Korea): yyyy-MM-dd  
Polish (Poland): yyyy-MM-dd  
Albanian (Albania): yyyy-MM-dd  
Swedish (Sweden): yyyy-MM-dd  
Khmer (Cambodia): yyyy-MM-dd  
Sinhala (Sri Lanka): yyyy-MM-dd  
Sami, Northern (Sweden): yyyy-MM-dd  
French (Canada): yyyy-MM-dd  
Sami, Lule (Sweden): yyyy-MM-dd  
Sami, Southern (Sweden): yyyy-MM-dd  
Sami (Southern): yyyy-MM-dd  
Sami (Lule): yyyy-MM-dd  


来源:https://stackoverflow.com/questions/26650839/datetime-tryparse-different-results

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