Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC View nullable Date field formatting

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

like image 437
Nate Pet Avatar asked Nov 30 '11 19:11

Nate Pet


2 Answers

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

@string.Format("{0:MM/dd/yyyy}", item.CreatedByDt)
like image 142
dotjoe Avatar answered Nov 15 '22 02:11

dotjoe


@(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.

like image 42
Alain Terrieur Avatar answered Nov 15 '22 02:11

Alain Terrieur