Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert javascript variable “11:00 AM” to c# equivalent where SQL is in time format

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".

like image 371
Muzafar Khan Avatar asked Feb 04 '26 03:02

Muzafar Khan


1 Answers

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;
    }            
}
like image 197
Minh Nguyen Avatar answered Feb 06 '26 15:02

Minh Nguyen