Assign format of DateTime with data annotations?

Steven picture Steven · Mar 9, 2011 · Viewed 211.7k times · Source

I have this attribute in my view model:

[DataType(DataType.DateTime)]
public DateTime? StartDate { get; set; }

If I want to display the date, or populate a textbox with the date, I have these:

<%: Model.StartDate %>

<%: Html.TextBoxFor(m => m.StartDate) %>

Whenever the date is displayed, it's displayed like: 01/01/2011 12:00:00 AM

But I'd like to only display 01/01/2011

Is there a way to apply a display format with data annotations? I don't want to have to go to every instance where I display a date, and add some code to format it.

Answer

David Fox picture David Fox · Mar 9, 2011

Try tagging it with:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]