The problem here is that the DateTime?
has no ToString()
method which accepts formatting string. To overcome this, you can use the following piece of code:
@string.Format("{0:ddd dd mmm yyyy}", item.DailyReportDate)
If DailyReportDate
is null
, then this code will render as an empty string. Otherwise, you get your formatted datetime. This behavior is described in Nullable.ToString Method documentation
Hope that helps.
Not exactly what you want, but this can help you.
If you had a simple DateTime
(non-nullable), then here is a good example on how to accomplish what you want. To summarize, all you need to do is to set a DisplayFormatAttribute
attribute on your property
public class Model {
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime? DailyReportDate { get; set;}
}
and then you can use it like pointed out:
@Html.DisplayFor(item=> item.DailyReportDate)
You can find the documentation for DisplayFormatAttribute
here