10

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

Community
  • 1
  • 1
fares Ayyad
  • 333
  • 1
  • 7
  • 17

2 Answers2

9

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

Der Kommissar
  • 5,848
  • 1
  • 29
  • 43
3

if you look at documentation of DisplayFormatAttribute.DataFormatString Property you will see

Gets or sets the display format for the field value.

it is not mentioned that it will change the design format of the datepicker, it only chages the format of the value. since you are getting date from HTML 5 date picker you cannot change its format Is there any way to change input type=“date” format? and also some browsers does not support HTML 5 date picker but you can use jquery date picker

add this in head

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

and in body

@Html.TextBoxFor(m => m.DesignVacation.DepartureDate)

and finally add script

<script>

   $(function(){

       $('#DesignVacation_DepartureDate').datepicker({
        dateFormat: 'dd/mm/yy'
    });

});

</script>
Community
  • 1
  • 1
Usman
  • 4,615
  • 2
  • 17
  • 33