TryParseExact returns false, though I don't know why

守給你的承諾、 提交于 2019-12-01 15:23:25

问题


Method TryParseExact in code block below returns true.
I would like to know why.
I think this date "2013.03.12" is invalid because this is not separated by slash but dot.

After I changed the CultureInfo "de-De" to "en-US", the method returns false. This could be a hint but I still don't know why this happens.

var format = new string[] { "yyyy/MM/dd" };
var parsed = new DateTime();
var result = DateTime.TryParseExact("2013.03.12", format, 
             new CultureInfo("de-DE"), DateTimeStyles.None, out parsed);

回答1:


I think your current DateSeparator is . (dot) and / automaticly replace itself to it.

/ seperator has a special meaning of "replace me with the current culture's date separator"

CultureInfo c = new CultureInfo("de-DE");
Console.WriteLine(c.DateTimeFormat.DateSeparator); //Prints . (dot)

Take a look at The "/" Custom Format Specifier




回答2:


As @Soner Gönül points out, the / is taken as "the date separator" in custom format strings. If you want to only accept / characters, you need to escape them:

var format = new string[] { @"yyyy\/MM\/dd" };


来源:https://stackoverflow.com/questions/18350301/tryparseexact-returns-false-though-i-dont-know-why

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