问题
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