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

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


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())


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@Model.ToShortDateString()

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

@Html.DisplayFor(m => m.MyDateTime, "ShortDateTime")


Simple formatted output inside of the model

@String.Format("{0:d}", model.CreatedOn)

or in the foreach loop

@String.Format("{0:d}", item.CreatedOn)