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

Slauma picture Slauma · May 14, 2011 · Viewed 214.2k times · Source

If I have in my model class a property of type DateTime how can I render it in a specific format - for example in the format which ToLongDateString() returns?

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 val contains the expected value, as I could see in the debugger).

Thanks for tips in advance!

Edit

ToLongDateString is only an example. What I actually want to use instead of ToLongDateString is a custom extension method of DateTime and DateTime?:

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

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

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

Answer

Darin Dimitrov picture Darin Dimitrov · May 14, 2011

You could decorate your view model property with the [DisplayFormat] attribute:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", 
               ApplyFormatInEditMode = true)]
public DateTime MyDateTime { get; set; }

and in your view:

@Html.EditorFor(x => x.MyDate)

or, for displaying the value,

@Html.DisplayFor(x => x.MyDate)

Another possibility, which I don't recommend, is to use a weakly typed helper:

@Html.TextBox("MyDate", Model.MyDate.ToLongDateString())