Reputation: 975
I am using ASP.Net with MVC and trying to display dates without the time. I have two dates, a StartDate and EndDate. I am able to display the StartDate without the time however having trouble with the EndDate. From my reading, I believe it is due to it being a nullable date. My EndDate is defined as:
public Nullable<System.DateTime> EndDate { get; Set; }
While my display is:
@Html.DisplayFor(modelItem => item.EndDate)
I was able to display my StartDate by defining a new string:
public string ReturnStartDateForDisplay {
get
{
return this.StartDate.ToString("d");
}
}
and displaying it with:
@Html.DisplayFor(model.Item => item.ReturnStartDateForDisplay)
Upvotes: 0
Views: 1496
Reputation: 2031
You can do this
public string ReturnEndDateForDisplay
{
get
{
return this.EndDate.HasValue ? this.EndDate.Value.ToString("d"): string.Empty;
}
}
And use like this:
@Html.DisplayFor(model.Item => item.ReturnEndDateForDisplay)
Upvotes: 2
Reputation: 751
You don't need to define a new ReturnStartDateForDisplay
property. Use System.ComponentModel.DataAnnotations and decorate your StartDate
and EndDate
with a DisplayFormat
attribute:
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime StartDate{ get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? EndDate{ get; set; }
Null values will be magically handled for you.
Upvotes: 2