I’ve been struggling with this issue while developing an MVC application in Asp.Net Core 2.0. There really doesn’t seem to be a complete perfect solution for all browsers.
The solution provided by erdinger above does not address the issue for someone using the asp-for= attribute in an Asp.Net Core 2.0 application. Furthermore, if you are using Entity Framework to generate migrations to the database, removing the [DataType(DataType.Date)]
attribute in the model will result in the datatype in your database table being created (or changed) to a text type when you may in fact require a date type in your database table. I would suggest leaving the [DataType(DataType.Date)]
attribute alone.
As I said above, there is no perfect solution for all browsers. So, what I did was to compromise slightly by not requiring an exact format for the edit form while still keeping my special format for all other displays of the date.
Here is the DateCompleted part of my model:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}", ApplyFormatInEditMode = false)]
[Display(Name = "Date Completed")]
public DateTime DateCompleted { get; set; }
As you might notice, the main thing I changed is the bool value in the [DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}", ApplyFormatInEditMode = false)]
attribute.
I set it to false
instead of true
. You might also get the same results by eliminating the ApplyFormatInEditMode
part altogether.
such as: [DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]
The view code in razor syntax looks like this:
<div class="form-group">
<label asp-for="DateCompleted" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="DateCompleted" class="form-control" />
<span asp-validation-for="DateCompleted" class="text-danger"></span>
</div>
</div>
Given a date of January 26th 2016, the format for non-form input objects shows as Jan 26, 2016. However, the results in the edit form, although not exactly perfect render the date in Firefox and Internet Explorer as 2016-01-26. In Chrome and Edge, the result displays 1/26/2016 and allows these browsers’ built-in calendar popups to work flawlessly.
The good thing is that all these browsers display the desired date format in non-form input situations and still at least display a date in the form fields instead of displaying dd/mm/yyyy
.
I hope this helps.