Convert t formatted time string to TimeSpan


I am using the Kendo UI TimePicker for a TimeSpan property of my model.

My first problem is that the value of the TimePicker is not getting picked up by my view model, even though everything is named correctly.

My second problem is when I get the value from the form data, it is formatted as a string, such as “11:00 AM”. I was struggling to try to get this string into a TimeSpan type in C#. Note the TimeSpan type in C# is the mapping to the Time type in SQL server.


The solution to my first problem was to simply get the data from the Form instead of relying on it being set in my view model.

The solution to my second problem was to Parse the t formatted string as a DateTime instead of a TimeSpan, and then use the TimeOfDay property.

Works like a champ.

So my controller code is this:

editIncidentViewModel.IncidentCarrier.ScheduledPickupTime = TimeSpanHelper.ConvertTFormatToTimeSpan(this.Request.Form.Get("IncidentCarrier.ScheduledPickupTime"));

And my helper method is this:

public static TimeSpan? ConvertTFormatToTimeSpan(string stringToConvert)
if (string.IsNullOrEmpty(stringToConvert))
return null;

DateTime dateTime;
if (DateTime.TryParse(stringToConvert, out dateTime))
return dateTime.TimeOfDay;
return null;

Hope this helps someone!

Happy coding,
Tom Hundley

One response to “Convert t formatted time string to TimeSpan

  1. Thank you. Really helpful tip. But how to bind this value on view with model value.
    @(Html.Kendo().TimePicker().Name(“StartTime”).value(m => m.StartTime).Min(“8:00 AM”).Max(“6:00 PM”) .HtmlAttributes(new { style = “width:100px” }))

    This is not working ..



What are your thoughts?

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.