I'm trying to format some DateTimes in MVC but the DisplayFormat is not being applied to the Nullable object and I can't figure out why. It worked perfectly fine on CreatedDateTime but not LastModifiedDateTime
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy hh:mm tt}")]
public DateTime CreatedDateTime { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy hh:mm tt}")]
public Nullable<DateTime> LastModifiedDateTime { get; set; }
Below is the View
<div class="editor-field">
@Html.DisplayFor(model => model.CreatedDateTime)
<br />
@Html.Raw(TimeAgo.getStringTime(Model.CreatedDateTime))
</div>
@if (Model.LastModifiedDateTime.HasValue)
{
<div class="editor-label">
@Html.LabelFor(model => model.LastModifiedDateTime)
</div>
<div class="editor-field">
@Html.DisplayFor(model => model.LastModifiedDateTime)
<br />
@Html.Raw(TimeAgo.getStringTime(Model.LastModifiedDateTime.Value)) By: @Html.DisplayFor(model => model.LastModifiedBy)
</div>
}
If I understood your intentions correct (I hope I did), then you can have a display template for Nullable by placing your template in Views/Shared/DisplayTemplates/DateTime.cshtml
and define it like the following:
@model System.DateTime?
@Html.Label("", Model.HasValue ? Model.Value.ToString("MM/dd/yy hh:mm tt") : string.Empty)
I hope this helps.
EDIT
You can have multiple Display Templates for the same type and specify which one to use by name so let's say you have:
Views/Shared/DisplayTemplates/Name1.cshtml
Views/Shared/DisplayTemplates/Name2.cshtml
You can then call them like:
@Html.DisplayFor(model => model.LastModifiedDateTime, "Name1")
@Html.DisplayFor(model => model.LastModifiedDateTime, "Name2")
I think most simple way to format nullable DateTime
is to use ValueFor
method:
@Html.ValueFor(m => m.CreatedDateTime , "{0:MM/dd/yy hh:mm tt}")
@Html.ValueFor(m => m.LastModifiedDateTime , "{0:MM/dd/yy hh:mm tt}")
When using ValueFor
method with TimeSpan
or Nullable<TimeSpan>
, colon character ":" has to be escaped:
@Html.ValueFor(m => m.MyTimeSpan, "{0:hh':'mm}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With