ASP.NET MVC displaying date without time

梦想与她 提交于 2019-12-18 19:27:10

问题


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?


回答1:


Use DisplayFormatAttribute to indicate format when value is displayed. Also, you could create two DisplayTemplates, Date and DateTime, and use UIHintAttribute to specify template




回答2:


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.




回答3:


This should do it for edit mode and display

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

though if it is just display, this might work

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



回答4:


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

@Model.EventDate.ToShortDateString()
@Model.EventDate.ToLongDateString()



回答5:


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




回答6:


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

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



回答7:


If you are using MVC, perhaps you can try this on your client side script:

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


来源:https://stackoverflow.com/questions/6593238/asp-net-mvc-displaying-date-without-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!