The TimeSpan could not be parsed because at least one of the numeric components is out of range or contain too many digits

StackOverflow https://stackoverflow.com/questions/21874418

  •  13-10-2022
  •  | 
  •  

Question

Following code gives me error as shown in title above:

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

Just before the last line runs value of my_hours is 4.01:33:00. How do I fix this error?

Basically this code is running in a for loop and the value "25:07" keeps changing and it adds in my_hours and it keeps doing it until it tries to add this value "25:07" when current value of my_hours is 4.01:33:00 and throws error.

Était-ce utile?

La solution

Change the third line to my_hours += TimeSpan.Parse("00:25:07")

You can read about the expected format of TimeSpan.Parse() on MSDN:

The s parameter contains a time interval specification in the form:

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

So the bare minimum that is required is hh:mm. When you put in 25:07, it was interpreted as 25 hours, seven minutes, which is an illegal value (since hours need to be between 0-23).

Adding in 00: in front changes it to 0 hours, 25 minutes and 7 seconds, which is now a legal value to parse.

Autres conseils

If you want to use more than 24 hours, you have to use a different format. The format that Parse accepts is documented

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

So you have to specify 1.01:07 for 1 day, 1 hour and 7 minutes.

According to TimeSpan.Parse documentation, format of expected string is

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

Where hh is hours, ranging from 0 to 23. So, string 25:07 is considered as hh:mm string with hours having value 25. That gives you OverflowException.

If you want to add 25 hours, then you should add 1 day and one hour 1:01:07. If that supposed to be 25 minutes, then use format with seconds 00:25:07

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top