3

I have a model with a DateTime propery:

[DisplayName("Updated")]
public DateTime lastUpdatedDate { get; set; }

At the moment, I think I am incorrectly handling the formatting of the datetime in the view.

<tr>
    <td>@Html.LabelFor(m=>m.lastUpdatedDate)</td>
    <td>@Html.Label(Model.lastUpdatedDate.ToLongDateString())</td>
</tr>

I am sure this is wrong. Firstly, should I do the formatting in the model, and return string (In the model used for displaying the date - the Update model needs the DateTime type for the control)? But it gets complicated - timezones. Should I manipulate the value of the date time (based on a timezone selection by the user on registration) in the model on the get; .. thing? (What's the called? The getter?? hehe).

Just trying to make my code friendly to work with, while I learn MVC.

tereško
  • 58,060
  • 25
  • 98
  • 150
Craig
  • 18,074
  • 38
  • 147
  • 248

1 Answers1

1

If you want to elegantly deal with timezones, I suggest you read this answer. For simple formatting the DateTime property in your model, decorate it with the [DisplayFormat] attribute:

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

and in your view:

@Html.DisplayFor(x => x.lastUpdatedDate)
Community
  • 1
  • 1
chridam
  • 100,957
  • 23
  • 236
  • 235