Now I was searching for a free reliable TimePicker control to use in my MVC application until I got fed up with finding one and decided to make my own using by C#..
I did this and it works fine (feel free to copy or re-use..):
public static class OpeningTimesList
{
/// <summary>
/// Provides a listItems of opening hours to use in an HTML DropDownListFor helper.
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static List<SelectListItem> GetOpeningHours(string time)
{
var selectOptions = new string[]
{
"07:00",
"07:30",
"08:00",
"08:30",
"09:00",
"09:30",
"10:00",
"10:30",
"11:00",
"11:30",
"12:00",
"12:30",
"13:00",
"13:30",
"14:00",
"14:30",
"15:00",
"15:30",
"16:00",
"16:30",
"17:00",
"17:30",
"18:00",
"18:30",
"19:00",
"19:30",
"20:00",
"20:30",
"21:00",
"21:30",
"22:00",
"22:30"
};
return GetDropDownList(selectOptions, time);
}
/// <summary>
/// Gets List Items in Text only, instead of a combination of text and value.
/// </summary>
/// <param name="selectOptions"></param>
/// <param name="selectedOption"></param>
/// <returns></returns>
private static List<SelectListItem> GetDropDownList(string[] selectOptions, string selectedOption)
{
var listItems = new List<SelectListItem>();
foreach (var option in selectOptions)
{
listItems.Add(new SelectListItem
{
Text = option,
Selected = string.Compare(option, selectedOption, StringComparison.CurrentCultureIgnoreCase) == 0
});
}
return listItems;
}
}
Use-age in an MVC razor:
@Html.DropDownListFor(x => x.StartFrom, Website.ViewModels.ViewHelpers.OpeningTimesList.GetOpeningHours(Model.StartFrom.ToString()))
My problem is that my StartFrom
property is not string
; it is a TimeSpan
(or may be it should be a DateTime
.. I am ok with converting ToString()
or casting in the code behind but Ideally I shouldn't do this. Working with String
time items is easy - but what should I use to make this better; do I use DateTime
or do I use TimeSpan
.
So in one line: what would you use to represent a time value such as - for example: 08:30. Would you use a TimeSpan
or DateTime
?
Many thanks.
Neither. A DateTime represents a date and time, a TimeSpan a certain length of time. Your variable represent a certain repeating moment in time that can occur on any day.
So while having to compromise anyway, use the one that best fits your use case - or take a look at NodaTime's Period.
Of course it depends on what you want to do with the result. You can just use TimeSpan
and add it to a certain DateTime.Date
to add the hours and minutes from the TimeSpam to the day of the Date.