Monday, March 20, 2017

Remove Timestamp from a DateTime variable in MVC Razor

Issue

I needed to format some dates on a View and could not remember the syntax.

Define in your model a readonly variable

public String startDateFormatted { get { return String.Format("{0:dd/MM/yyyy}", startDate); } }
Then in the razor syntax just use DisplayFor

DisplayFor(modelItem => item.startDateFormatted)

OR

You can use the assign the date formatting attributes on the property of the model

[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
public DateTime? startDate { get; set; }

Source

http://stackoverflow.com/questions/11122171/asp-net-mvc-razor-remove-time-from-datetime-property

No comments:

Post a Comment