Saifu Rahman
Saifu Rahman

Reputation: 11

"TimeSpan" .Net Datatype in API Endpoint not accepting more than 24 hours. throwing validation error

Has anyone ever used "TimeSpan" datatype in C#? I am not able to post a value with more than 24 hours to the C# MVC controller. My DTO has a property with "TimeSpan" datatype. I need to give end customer the flexibility of using Timespan. I am now receiving the error in response:

Error converting value "59:42:33" to type 'System.Nullable`1[System.TimeSpan]'.

I am getting the below validation error while posting itself, not even hitting in the C# endpoint..

Response

and the Request json looks like:

{
"timeSinceStarted" : "59:42:33"
}

Upvotes: 1

Views: 887

Answers (2)

glenebob
glenebob

Reputation: 1973

Well this certainly seems strange to me, but I think I have the answer.

https://learn.microsoft.com/en-us/dotnet/api/system.timespan.parse?view=net-5.0#System_TimeSpan_Parse_System_String_

For example, the value of hh, the hours component, must be between 0 and 23. Because of this, passing "23:00:00" to the Parse method returns a time interval of 23 hours. On the other hand, passing "24:00:00" returns a time interval of 24 days. Because "24" is outside the range of the hours component, it is interpreted as the days component.

Because of this very strange logic, apparently, when you specify 24 hours (which becomes 24 days), the minute field is interpreted as hours, which cannot exceed 23. Sure enough, in my test, "24:23:00" is valid (and indeed parses to 24 days, 23 hours), while "24:24:00" is invalid.

This is a bug in my book, but since it's actually documented as correct, it cannot be fixed.

Upvotes: 1

M Arslan Riaz
M Arslan Riaz

Reputation: 128

Well, the simplest thing to do is to format this yourself for example code below

Instead of 59 hours, try 2 days and 11 hours (2.11:42:33)? The input probably goes to TimeSpan.TryParse() with the default format

Second way

return string.Format("{0}hr {1}mn {2}sec",
                 (int) span.TotalHours,
                 span.Minutes,
                 span.Seconds);

AND Third way is

string span = "35:15";
TimeSpan ts = new TimeSpan(int.Parse(span.Split(':')[0]),    // hours
                       int.Parse(span.Split(':')[1]),    // minutes
                       0);                               // seconds

Upvotes: -2

Related Questions