Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

timespan

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.

like image 948
Frank Martin Avatar asked Dec 26 '22 13:12

Frank Martin


2 Answers

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.

like image 93
Yaakov Ellis Avatar answered Jan 25 '23 23:01

Yaakov Ellis


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.

like image 20
Damien_The_Unbeliever Avatar answered Jan 25 '23 22:01

Damien_The_Unbeliever