@Html.DisplayFor – DateFormat (“mm/dd/yyyy”)

If you use DisplayFor, then you have to either define the format via the DisplayFormat attribute or use a custom display template. (A full list of preset DisplayFormatString‘s can be found here.)

[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? AuditDate { get; set; }

Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml:

@model DateTime?
@if (Model.HasValue)
{
    @Model.Value.ToString("MM/dd/yyyy")
}

That will apply to all DateTimes, though, even ones where you’re encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml and the DataType attribute on your property:

[DataType(DataType.Date)]
public DateTime? AuditDate { get; set; }

The final option is to not use DisplayFor and instead render the property directly:

@if (Model.AuditDate.HasValue)
{
    @Model.AuditDate.Value.ToString("MM/dd/yyyy")
}

Leave a Comment