I have some issue with displaying date correctly, using the MVC4 DateTime object.
In the controller, I set my date from a correct value from my database : Birthdate = person.Birthdate
In ViewModel:
[DisplayFormat(DataFormatString = "DD/mm/YY", ApplyFormatInEditMode = true, ConvertEmptyStringToNull = true)]
public DateTime? Birthdate { get; set; }
In View:
@using (Html.BeginHorizontalControlFor(m => m.Birthdate))
{
@Html.EditorFor(model => model.Birthdate)
@Html.ValidationMessageFor(model => model.Birthdate)
}
Output:
<input class="text-box single-line input-validation-error" data-val="true" data-val-date="The field Birthdate must be a date." id="Birthdate" name="Birthdate" type="datetime" value="DD/mm/YY">
Where is my date value? Why doesn’t it work?
DD/mm/YYis the wrong format – you’ve got the case wrong for all components. You should usedd/MM/yy(or something similar; personally I’d recommend usingyyyyinstead ofyy). See the MSDN documentation for custom date/time formats for more details.Also note that this is very culture-specific – are you sure that’s an appropriate format for all the cultures you’re targeting? (Using some sort of calendar control would be better from a usability perspective, I suspect.)