Date mismatch in browsers - MVC 5 date from model

I have this in my view model:

[Required]
[Display(Name = "Date of birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }

      

And on the form:

<div class="form-group">
      @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
             @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
             @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
      </div>
</div>

      

Works well in all browsers except Chrome which only displays "dd / MM / yyyy" instead of populating the field with a value from the model.

So I tried to change the date format in the ViewModel:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

      

Chrome starts showing model value in dd / MM / yyyy format (maybe due to my local region settings?), But all other browsers start showing yyyy-MM-dd format.

I understand that this is an internationally recognized standard, but as an Australian site, the design we worked with was in dd / MM / yyyy format.

Can I get it to work so that all browsers display dd / MM / yyyy without having to resort to:

@Html.TextBoxFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" }, @Value = Model.DateOfBirth.ToString("dd/MM/yyyy") })

      

This means that Chrome does not provide date picker functionality.

Using latest MVC with C # view model. Opera appears to behave similarly to Chrome.

+2


source to share


2 answers


We ended up using only separate dropdowns for the day, month, year fields. I guess another option would be to find a datepicker plugin that worked in all browsers (and mobile). It's a shame!



0


source


It looks like Chrome only accepts the format yyyy-MM-dd

, so the following will work

[Required]
[Display(Name = "Date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }

      

Then the assigned date will be displayed (using regional settings) rather than the date string. I think this has the advantage that a user in a different culture will see the date in their culture and not yours.



This is really according to the specifications

It doesn't help much if you are also using @Html.DisplayFor(m=> m.DateOfBirth)

. One way would be to create a DisplayTemplate DateTime.cshtml

that formats the date string with.ToString("dd/MM/yyyy")

+1


source







All Articles