TimeSpan timeTaken = TimeSpan.Parse("51:45:33");
给我错误:
An exception of type 'System.OverflowException' occurred in mscorlib.dll but was not handled in user code
Additional information: The TimeSpan could not be parsed because at least one of the numeric components is out of range or contains too many digits.
为什么?
最佳答案
考虑 TimeSpan.Parse 的文档带有单个字符串参数的方法。
输入字符串的格式为:
[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]
为简单起见,只考虑[d.]hh:mm[:ss]
部分,其中d
和ss
是天数和秒,它们是可选的。
hh
部分是小时,范围从0到23。d
组件是 天,范围从 0 到 10675199。
在您的情况下,hh:mm:ss
格式的输入 51:45:33
具有等于 51 的 hh
组件,这就是您得到的原因溢出异常。天数最大可达10675199,所以需要从51小时中挑全天,也就是两天零三小时。
结果代码看起来像:
TimeSpan timeTaken = TimeSpan.Parse("2.3:45:33");
另请注意有关文化敏感符号 .
和 :
的信息。
为了验证答案,您可以打印总分钟数
Console.WriteLine(timeTaken.TotalMinutes); //prints 3105.55
Console.WriteLine(51 * 60 + 45 + 33f / 60); //also prints 3105.55
关于c# - TimeSpan.Parse 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25164724/