Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan.Parse Error

TimeSpan timeTaken = TimeSpan.Parse("51:45:33");

Gives me the error:

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.

Why?

like image 539
User1 Avatar asked Dec 21 '25 02:12

User1


2 Answers

Consider the documentation for TimeSpan.Parse method with single string parameter.
Format for input string is:

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

To make it simple, consider only [d.]hh:mm[:ss] part, where d and ss are days and seconds respectively and they are optional.

  • hh component is hours, ranging from 0 to 23.
  • d component is days, ranging from 0 to 10675199.

In your case hh:mm:ss formated input 51:45:33 has hh components equal to 51, that's why you get overflow exception. Days can be up to 10675199, so you need to pick full days from 51 hours, which is two days and three hours.

Resulting code will look something along:

TimeSpan timeTaken = TimeSpan.Parse("2.3:45:33");

Also notice information about culture-sensitive symbols . and :.

To verify answer, you can print total number of minutes

Console.WriteLine(timeTaken.TotalMinutes);     //prints 3105.55

Console.WriteLine(51 * 60 + 45 + 33f / 60);    //also prints 3105.55
like image 115
Ilya Ivanov Avatar answered Dec 22 '25 14:12

Ilya Ivanov


Here is your answer: http://msdn.microsoft.com/en-us/library/se73z7b9(v=vs.110).aspx

hh Hours, ranging from 0 to 23.

mm Minutes, ranging from 0 to 59.

ss Seconds, ranging from 0 to 59.

like image 29
Major Avatar answered Dec 22 '25 16:12

Major



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!