Format TimeSpan in 12-hour format with AM/PM in MVC Model and View

3.1k Views Asked by At

I have an MVC webpage contains a StartTime timepicker, so I want to view and save that time in 12-hour format with AM/PM. I've tried to format the TimeSpan in the Model and the View as shown below, but it doesn't work and shows "Input string was not in a correct format." error in the View. What should I do?

In Model:

public class Model
{
    .
    .
    [Required]
    [Display(Name = "Start Time")]
    [DataType(DataType.Time)]
    [DisplayFormat(DataFormatString = "{0:hh\\:mm\\:tt}", ApplyFormatInEditMode = true)]
    public TimeSpan StartTime { get; set; }
    .
    .
}

In View:

@Html.TextBoxFor(m => m.StartTime, "{0:hh\\:mm\\:tt}")
0

There are 0 best solutions below