Tuesday, January 14, 2014

How to format a date exactly as you want M/d/yyyy

I was having issues formatting a date in ASP.NET MVC3, and I tried everything to get my dates formatted M/d/yyyy. It turned out I needed to set the datatype to text. Before I did that, my dates had leading zeros, which is exactly what I did not want.
[DisplayName("Date Start")]
[DataType(DataType.Text)]
[DisplayFormat(DataFormatString = "{0:M/d/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? DateStart { get; set; }
Remember to use @Html.EditorFor to get the formatting to come through. TextBoxFor will not look at display format, even if ApplyFormatInEditMode is true.