Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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: enter image description here

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).