C# – ASP.NET MVC displaying date without time

asp.net-mvcattributescdata-annotationsdatetime

I have my model field decorated in the following way:

[DataType(DataType.Date)]
[Display(Name = "Date of birth")]
public string DateOfBirth { get; set; }

When I want to display the value in the view using the following code:

<%: Html.DisplayFor(m => m.DateOfBirth) %>

The problem is that the date is displayed together with its time value. I wonder why it does not take DateType attribute into consideration and displays only the date value without time. I know that I may create a display template for DateTime but in other cases than date of birth I want to show time together with date. How to solve the problem?

Best Answer

The problem you have here is that you are using a string value rather than a DateTime.

change your model to be:

[DataType(DataType.Date)]
[Display(Name = "Date of birth")]
public DateTime? DateOfBirth { get; set; }

DataType will only work if it's a DateTime type, you also get the added advantage that it will automatically validate it as a valid date when using a DateTime. If you use string, you will have to use a regular expression validator to ensure a proper date has been entered.