无法解析 TimeSpan,因为至少有一个数字组件超出范围或包含太多数字

Fra*_*tin 4 c# timespan

以下代码给了我上面标题所示的错误:

TimeSpan my_hours = new TimeSpan();
my_hours = TimeSpan.Parse("00:00");
my_hours += TimeSpan.Parse("25:07"); //this line throws error
Run Code Online (Sandbox Code Playgroud)

就在最后一行运行之前,my_hours 的值为 4.01:33:00。我该如何解决这个错误?

基本上,这段代码在 for 循环中运行,并且值“25:07”不断变化,并添加到 my_hours 中,并一直这样做,直到当 my_hours 的当前值为 4.01:33 时,它尝试添加此值“25:07” :00 并抛出错误。

Yaa*_*lis 5

将第三行更改为 my_hours += TimeSpan.Parse("00:25:07")

您可以TimeSpan.Parse() 在 MSDN 上阅读有关预期格式的信息

s 参数包含以下形式的时间间隔规范:

[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]

因此,所需的最低限度是hh:mm. 当你输入时25:07,它被解释为 25 小时 7 分钟,这是一个非法值(因为小时需要在 0-23 之间)。

00:在前面添加将其更改为 0 小时 25 分 7 秒,这是现在解析的合法值。