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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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 )

Google+ photo

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

Connecting to %s