ASP.NET MVC displays date without time

I have my model field, styled as follows:

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

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

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

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

+11
source share
7 answers

Use DisplayFormatAttribute to specify the format when the value is displayed. Alternatively, you can create two DisplayTemplates, Date and DateTime, and use UIHintAttribute to specify the template.

+4
source

The problem is that you are using a string value, not a DateTime.

change your model:

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

DataType will only work if it is a DateTime type, you also get the added benefit of automatically checking it as a valid date when using DateTime. If you use a string, you will need to use a regular expression checker to ensure the correct date.

+11
source

This should be done for editing and display mode.

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

although if it’s just a display, it may work

 [DisplayFormat(DataFormatString = "{0:d}")] 
+9
source

You can use ToShortDateString () or ToLongDateString () to display only the date, for example:

 @Model.EventDate.ToShortDateString() @Model.EventDate.ToLongDateString() 
+4
source

If your date is of type DateTime and ToShortDateString() or ToLongDateString() still doesn't work, check if your DateTime can be null (DateTime?). Making it nullify can do the trick.

+2
source

using @Value and ToShortDateString (), you can only display the date.

 @Html.TextBoxFor(model => model.StartDate, "", new { id = "date", @class = "datepicker", @style = "width:70%; height:30px;", @placeholder = "Enter Date", @Value = @Model.StartDate.ToShortDateString()}) 
0
source

If you use MVC, maybe you can try this on your client script:

 @{ string birthDateOnly = Model.DateOfBirth.Date.ToShortDateString(); } @Html.DisplayTextFor(m => birthDateOnly) 
0
source

All Articles