Slauma Slauma - 1 year ago 133
ASP.NET (C#) Question

How to render a DateTime in a specific format in ASP.NET MVC 3?

If I have in my model class a property of type

how can I render it in a specific format - for example in the format which

I have tried this...

@Html.DisplayFor(modelItem => item.MyDateTime.ToLongDateString())

...which throws an exception because the expression must point to a property or field. And this...

@{var val = item.MyDateTime.ToLongDateString();
Html.DisplayFor(modelItem => val);

...which doesn't throw an exception, but the rendered output is empty (although
contains the expected value, as I could see in the debugger).

Thanks for tips in advance!


is only an example. What I actually want to use instead of
is a custom extension method of

public static string FormatDateTimeHideMidNight(this DateTime dateTime)
if (dateTime.TimeOfDay == TimeSpan.Zero)
return dateTime.ToString("d");
return dateTime.ToString("g");

public static string FormatDateTimeHideMidNight(this DateTime? dateTime)
if (dateTime.HasValue)
return dateTime.Value.FormatDateTimeHideMidNight();
return "";

So, I think I cannot use the
attribute and
parameter on the ViewModel properties.

Answer Source

If all you want to do is display the date with a specific format, just call:

@String.Format(myFormat, Model.MyDateTime)

Using @Html.DisplayFor(...) is just extra work unless you are specifying a template, or need to use something that is built on templates, like iterating an IEnumerable<T>. Creating a template is simple enough, and can provide a lot of flexibility too. Create a folder in your views folder for the current controller (or shared views folder) called DisplayTemplates. Inside that folder, add a partial view with the model type you want to build the template for. In this case I added /Views/Shared/DisplayTemplates and added a partial view called ShortDateTime.cshtml.

@model System.DateTime


And now you can call that template with the following line:

@Html.DisplayFor(m => m.MyDateTime, "ShortDateTime")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download