Pedro Lopes Pedro Lopes - 28 days ago 8
C# Question

Trying to convert DateTime to ShortDateString in razor code

Currently my DateTime gets displayed as this in my view example: 03/08/2017 00:00:00. I want it to be displayed as follow: 03/08/2017 without the time being displayed. This is my current view code

@foreach (var item in Model)
@Html.DisplayFor(modelItem => item.DayOfMonth)
@Html.DisplayFor(modelItem => item.TimeSpent) hr
@Html.DisplayFor(modelItem => item.Project.Name)
@Html.DisplayFor(modelItem => item.Task.Name)

@Html.ActionLink("Edit", "Edit", new { id = item.IdTimeSheet_Details }) |
@Html.ActionLink("Details", "Details", new { id = item.IdTimeSheet_Details }) |
@Html.ActionLink("Delete", "Delete", new { id = item.IdTimeSheet_Details })

What i have tried so far:

@Html.DisplayFor(modelItem => item.DayOfMonth, "{0:MM/dd/yyyy}")
@Html.DisplayFor(modelItem => item.DayOfMonth.Date.ToString("dd MMM yyyy"))
@Html.DisplayFor(modelItem => item.DayOfMonth.Value.ToString("dd. MM. yyyy"))
@Html.DisplayFor(modelItem => item.DayOfMonth.ToShortDateString() : string.Empty))
@Html.DisplayFor(modelItem => item.DayOfMonth.ToString("dd MMM yyyy"))
@Html.DisplayFor(modelItem => item.DayOfMonth.Value.ToString("dd - M - yy"))

None of the above has worked. Can someone tell me what im doing wrong?
The exeption im getting is

Templates can be used only with field access, property access,
single-dimension array index, or single-parameter custom indexer

But i dont really see what im doing differently from the people in the posts below:

Where i got most of the things i have tried from

Other post i have checked

Answer Source

You need to either use just

<td>item.DayOfMonth.ToString("dd MMM yyyy")</td>

or if you want to use DisplayFor(), then apply a

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime DayOfMonth { get; set; }

to your property and in the view

<td>@Html.DisplayFor(modelItem => item.DayOfMonth)</td>