In MVC Razor view, I am trying to format a DateTime field to display time only. Using below code I am getting error \"Templates can be used only with field access, property acce
Another possible approach could be using extension methods to achieve the same. Using that approach you will not be populating your views with hard coded format.
Extension Method
///
/// Converts a DateTime string to Date string. Also if Date is default value i.e. 01/01/0001
/// then returns String.Empty.
///
/// Input DateTime property
/// Pass true to show only date.
/// False will keep the date as it is.
///
public static string ToString(this DateTime inputDate, bool showOnlyDate)
{
var resultDate = inputDate.ToString();
if (showOnlyDate)
{
if (inputDate == DateTime.MinValue)
{
resultDate = string.Empty;
}
else
{
resultDate = inputDate.ToString("dd-MMM-yyyy");
}
}
return resultDate;
}
View
@Model.LastUpdateDate.ToString(true).
Link: DateTime to Date in ASP.net MVC