3

I try to format the datetime in the view.

<span class="tag">
        @Html.DisplayFor(modelItem => item.PostDate.ToString("yyyy"))  
</span>

here's the error message I got.

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

how do i fix it?

Mansoor Gee
  • 1,071
  • 8
  • 20
qinking126
  • 11,385
  • 25
  • 74
  • 124
  • 1
    This question is answered here http://stackoverflow.com/questions/6001654/how-to-render-a-datetime-in-a-specific-format-in-asp-net-mvc-3 – kmcc049 Sep 09 '11 at 01:45
  • 1
    to answer my own question: @item.PostDate.ToString("dd MMM yyyy") – qinking126 Sep 09 '11 at 02:25

3 Answers3

4

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

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

and in your view you simply use the Html.DisplayFor method:

<span class="tag">
    @Html.DisplayFor(modelItem => item.PostDate)
</span>

or you could also use:

<span class="tag">
    @item.PostDate.ToString("yyyy")
</span>

but if you had this in many places the first approach is preferable because the format will be centralized in a single location.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

@Html.DisplayFor(modelItem => item.PostDate).ToString().Substring(5,4)

So you can cut any part of your DateTime formatted field.

Amit
  • 15,217
  • 8
  • 46
  • 68
0

You can format your DateTime in the following way. It shows full date and time.

[DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
public DateTime PostDate { get; set; }

Then use it into View like this.

@Html.DisplayFor(model => model.PostDate)
Mansoor Gee
  • 1,071
  • 8
  • 20