解析看似正确的时间跨度时抛出异常 [英] Exception thrown when parsing seemingly correct time span
问题描述
我正在使用 TimeSpan.ParseExact
方法来解析时间跨度.但是,为什么下面会失败并抛出异常?
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);
从 MSDN 上的 Custom Date and Time Format Strings 文章来看,此输入字符串的格式正确.有什么想法吗?
Judging from the Custom Date and Time Format Strings article on MSDN, the format is correct for this input string. Any ideas?
推荐答案
您已链接到自定义 DateTime
格式说明符 - 但您没有解析为 DateTime
,您'正在解析为 TimeSpan
,因此您需要 自定义 TimeSpan
格式说明符 - 这意味着使用hh"而不是HH".此外,根据文档,您需要转义冒号 - 所以您真的想要:
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.
这篇关于解析看似正确的时间跨度时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!