I have following model properties
public class CallLog
{
public int CallLogID { get; set; }
public TimeSpan endTime { get; set; }
public TimeSpan startTime { get; set; }
}
my api call is "/api/CallLog/AddCallLog". where CallLog data contain
startTime = "11:00 AM"
endTime = "11:30 AM"
And my api controller is
[HttpPost]
public IHttpActionResult AddCallLog(CallLog callLog)
{
if (!ModelState.IsValid)
{
return Json(new
{
success = false,
errors = ModelState.Keys.SelectMany(k => ModelState[k].Errors)
.Select(m => m.ErrorMessage).ToArray()
});
}
CallLog.InsertCallLog(callLog);
return CreatedAtRoute("DefaultApi", new { id = callLog.CallLogID }, callLog);
}
It gives me the following error
{"Error converting value \"11:00 AM\" to type 'System.TimeSpan'. Path 'startTime'....}
{"Error converting value \"11:30 AM\" to type 'System.TimeSpan'. Path 'endTime'....}
My question is what datatype i need for time like "11:00 AM". Remember my datatype in database for startTime and endTime is "time".
From what the errors are saying, you may have to provide the correct conversion from string type "11:30 AM" to TimeSpan type. You could use DateTime.ParseExact with the convert pattern through parameter like this:
string pattern = "HH:mm 'AM'";
TimeSpan yourTimeSpan = DateTime.ParseExact(
"11:30 AM",
pattern,
CultureInfo.InvariantCulture
).TimeOfDay;
It will give you timespan with value 11:30:00
So, you may modify your code to something like this:
private string _endTime;
public TimeSpan endTime
{
get
{
return DateTime.ParseExact(
_endTime,
"HH:mm 'AM'",
CultureInfo.InvariantCulture
).TimeOfDay;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With