MVC View nullable Date field formatting

2019-04-03 13:17发布

问题:

I am trying to display the following in a view but is giving a problem:

    <td>
     @item.CreatedByDt.ToString("MM/dd/yyyy") 
    </td>  

Any idea on how to handle a nullable Date field in a view. I am using Razor by the way.

I am getting the following error:

No overload for method 'ToString' takes 1 arguments

回答1:

If you don't know if it will be null or not...

@string.Format("{0:MM/dd/yyyy}", item.CreatedByDt)


回答2:

@(item.CreatedByDt.HasValue ? item.CreatedByDt.Value.ToString("MM/dd/yyyy") : "--/--/----")

You can replace the display string for when your date is null with what you want.



回答3:

@item.CreatedByDt.Value.ToString("MM/dd/yyyy")


回答4:

@item.PostDatePublished.Value.ToString

need the value in there