Format Date with culture in Razor @Html.EditFor

2019-07-13 07:55发布

问题:

MVC 4, C#.

In my razor view I have:

@Html.EditorFor(model => model.ActionObject.StartDate)

Which is annotated in my model with:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public System.DateTime? StartDate { get; set; }

In the view, it is set like so, with date picker:

Notice how it is mm/dd/yyyy. How can I change this dynamically based on the user? The user can set there culture to whatever they want.

Normally I can do:

.ToString("d", culture)

Where culture is set dynamically. But this doesn't work for @Html.Editfor.

回答1:

This datepicker is the native representation for HTML 5 input type date in Google Chrome. You can't change this format. The display format comes from user Culture / Localization config in his OS.

If you want to format this as you want, remove the [DataType(DataType.Date)], rendering a default input field and then use a JQuery UI DatePicker or another one to render a better date field.