Specify Date format in MVC5 (dd/MM/yyyy)

You’re generating the browser’s HTML5 datepicker by using EditorFor() in conjunction with the [DataType] and [DisplayFormat] attributes. The specifications require that the format be yyyy-MM-dd (ISO format). Change the attribute to:

[Required(ErrorMessage = "Departure date is required")]
[Display(Name = "Departure Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DepartureDate { get; set; }

and the date will be displayed in the culture of the user’s device, which is what the HTML-5 datepicker is for.

Note that you do not need a custom model binder (the date will be posted in ISO format and will be correctly bound by the DefaultModelBinder).

Note however that the HTML-5 datepicker is only supported in Chrome and Edge, and a normal textbox will be displayed in Firefox (for example). If you want a consistent UI, then it is recommended you use a jquery datepicker plugin (e.g. jquery-UI) but you will also need to reconfigure the validator for client side validation (refer to this answer for an example).

Leave a Comment