Specify Date format in MVC5 (dd/MM/yyyy)
asp.net, asp.net-mvc, c#, date, datetime
Solution
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).
Problem
I'm trying to handle user input for date values, I want to prompt user to input date in this format: dd/MM/yyyy what I tried to do: I read and implement the answer for Darin in this question: Format datetime in asp.net mvc 4 This is my implementation: In Global.asax ``` (ControllerContext controllerContext, ModelBindingContext bindingContext) { var displayFormat = bindingContext.ModelMetadata.DisplayFormatString; var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (!string.IsNullOrEmpty(displayFormat) && value != null) { DateTime date; displayFormat = displayFormat.Replace ("{0:", string.Empty).Replace("}", string.Empty); if (DateTime.TryParse(value.AttemptedValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { return date; } else { bindingContext.ModelState.AddModelError( bindingContext.ModelName, string.Format("{0} is an invalid date format", value.AttemptedValue) ); } } return base.BindModel(controllerContext, bindingContext); } ``` Departure Date in Model: ``` [Required(ErrorMessage = "Departure date is required")] [Display(Name = "Departure Date")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public DateTime DepartureDate { get; set; } ``` In view: ``` <div class="col span-1-of-2"> @Html.LabelFor(m => m.DesignVacation.DepartureDate) @Html.EditorFor(m => m.DesignVacation.DepartureDate) </div> ``` And this is the output when run the view: It starts with month(mm) but what I want is this format: dd/MM/yyyy How to get this format using editorFor(and if possible with textboxFor).