21

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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

5 Answers5

36

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

@string.Format("{0:MM/dd/yyyy}", item.CreatedByDt)
dotjoe
  • 26,242
  • 5
  • 63
  • 77
12
@(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.

Alain Terrieur
  • 121
  • 1
  • 3
0

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>
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
MAXE
  • 4,978
  • 2
  • 45
  • 61
0
@item.CreatedByDt.Value.ToString("MM/dd/yyyy")
Dima Pasko
  • 1,170
  • 12
  • 20
-2
@item.PostDatePublished.Value.ToString

need the value in there

Ashok Padmanabhan
  • 2,110
  • 1
  • 19
  • 36