Exception thrown when parsing seemingly correct time span

非 Y 不嫁゛ 提交于 2019-12-11 14:11:56

问题


I am using the TimeSpan.ParseExact method to parse a time span. However, why does the following fail and throw an exception?

string time = "23:10:00";
string format = "HH:mm:ss";
TimeSpan timeSpan = TimeSpan.ParseExact(time, format, CultureInfo.InvariantCulture);

Judging from the Custom Date and Time Format Strings article on MSDN, the format is correct for this input string. Any ideas?


回答1:


You linked to the custom DateTime format specifiers - but you're not parsing to DateTime, you're parsing to TimeSpan, so you need the custom TimeSpan format specifiers - which means using "hh" instead of "HH". Additionally, as per the documentation, you need to escape the colons - so you really want:

string format = @"hh\:mm\:ss";

I've validated that this works with your sample value.



来源:https://stackoverflow.com/questions/12731559/exception-thrown-when-parsing-seemingly-correct-time-span

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