简体   繁体   中英

Can my MVC view display only the date portion of a SQL datetime field?

I have an ASP.NET MVC4 application that is displaying the full datetime value from SQL (eg "1/1/2012 12:00:00 AM") and I'm trying to get it to only display the date (eg "1/1/2012").

My Index.cshtml file for the view in question pull the item in using this code:

@Html.DisplayFor(modelItem => item.OccurrenceDate)

Is there a way to modify this to only show the date?

You can also decorate your model with an annotation and the formatting will be handled for you

using System.ComponentModel.DataAnnotations;
class myModel {
  [DataType(DataType.Date)]
  public DateTime OccurencDate {get;set;}
}

您可以只使用 Date属性的 ToShortDateString()方法:

@Html.DisplayFor(modelItem => item.OccurrenceDate.ToShortDateString())

There is no need to use Html Helper DisplayFor unless you are taking an advantage of templates, which this helper is actually designed to do.

For your case just write:

@Model.OccurrenceDate.ToString("M/d/yyyy")

This is work for me
@item.OpeningDate.Value.ToShortDateString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM