Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DisplayFormat not working with Nullable<DateTime>

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>
    }
like image 369
Preston Avatar asked Jun 04 '13 02:06

Preston


2 Answers

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")
like image 145
Dimitar Dimitrov Avatar answered Oct 12 '22 15:10

Dimitar Dimitrov


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}")
like image 35
Nenad Avatar answered Oct 12 '22 14:10

Nenad