Nate Pet
Nate Pet

Reputation: 46222

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

Upvotes: 22

Views: 17184

Answers (5)

MAXE
MAXE

Reputation: 5122

If DateTime? is a null value, they give an error.

This solution will not generate an error:

@functions{
    string FormatNullableDate(DateTime? value) => value.HasValue ? value.Value.ToString("MM/dd/yyyy") : "-";
}

<td>
@FormatNullableDateTime(item.CreatedByDt)
</td>

Upvotes: 0

Alain Terrieur
Alain Terrieur

Reputation: 121

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

Upvotes: 12

dotjoe
dotjoe

Reputation: 26940

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

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

Upvotes: 36

Dima Pasko
Dima Pasko

Reputation: 1170

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

Upvotes: 0

Ashok Padmanabhan
Ashok Padmanabhan

Reputation: 2120

@item.PostDatePublished.Value.ToString

need the value in there

Upvotes: -2

Related Questions