Rehan Shah
Rehan Shah

Reputation: 1627

How to format DateTime in case of Nullable?

How to get .Tostring() Overloads for Nullable Datetime? ?

e.g

public DateTime BirthDate { get; set; }

In Case of above Code i can format BirthDate.

But in case of below Code i can't get All Overloads of .ToString() method.

public DateTime? BirthDate { get; set; }

I am actually want to apply format to BirthDate in Razor Syntax ?

E.g

<li><b>BirthDate</b> : @Model.BirthDate.ToString("dd/MM/yyyy")</li> // But this is not working.

How to applying format for BirthDate in case of Nullable ?

Upvotes: 4

Views: 3331

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112279

You can use null-conditional Operators (available since C# 6.0).

string s = BirthDate?.ToString("dd/MM/yyyy");

This returns null if BirthDate has no value (is null), i.e. ToString will not be called in this case. If you want to return a text in this case instead, you can use the null-coalescing operator

string s = BirthDate?.ToString("dd/MM/yyyy") ?? "none";

or you can use the ternary conditional operator (works with older C# versions)

string s = BirthDate.HasValue ? BirthDate.Value.ToString("dd/MM/yyyy") : "none";

or with the newer pattern matching (C# 7.0)

string s = BirthDate is DateTime d ? d.ToString("dd/MM/yyyy") : "none";

In Razor, apply this in parentheses (the ? seems to confuse Razor):

<li><b>BirthDate</b> : @(Model.BirthDate?.ToString("dd/MM/yyyy"))</li> 

or

<li>
    <b>BirthDate</b> : @(BirthDate.HasValue ? BirthDate.Value.ToString("dd/MM/yyyy") : "")
</li> 

Upvotes: 11

Related Questions