Exception thrown when parsing seemingly correct ti

2019-08-29 11:04发布

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条回答
唯我独甜
2楼-- · 2019-08-29 11:56

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.

查看更多
登录 后发表回答