在Nullable的情况下如何格式化DateTime?

Reh*_*hah -2 c# asp.net-mvc

如何获得.Tostring()Nullable的Overloads Datetime?

例如

public DateTime BirthDate { get; set; }
Run Code Online (Sandbox Code Playgroud)

在上述代码的情况下,我可以格式化BirthDate.

但是在下面的Code的情况下我无法获得All Overloads .ToString()方法.

public DateTime? BirthDate { get; set; }
Run Code Online (Sandbox Code Playgroud)

我实际上想在Razor语法中将格式应用于BirthDate?

例如

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

如果在Nullable的情况下应用BirthDate的格式?

Oli*_*bes 5

您可以使用空条件运算符(自C#6.0起可用).

string s = BirthDate?.ToString("dd/MM/yyyy");
Run Code Online (Sandbox Code Playgroud)

null如果BirthDate没有值(为null)则返回,即ToString在这种情况下不会被调用.如果您想在此情况下返回文本,则可以使用null-coalescing运算符

string s = BirthDate?.ToString("dd/MM/yyyy") ?? "none";
Run Code Online (Sandbox Code Playgroud)

或者您可以使用三元条件运算符(适用于较旧的C#版本)

string s = BirthDate.HasValue ? BirthDate.Value.ToString("dd/MM/yyyy") : "none";
Run Code Online (Sandbox Code Playgroud)

在Razor中,将其应用于括号中(?似乎混淆了Razor):

<li><b>BirthDate</b> : @(Model.BirthDate?.ToString("dd/MM/yyyy"))</li> 
Run Code Online (Sandbox Code Playgroud)

要么

<li>
    <b>BirthDate</b> : @(BirthDate.HasValue ? BirthDate.Value.ToString("dd/MM/yyyy") : "")
</li> 
Run Code Online (Sandbox Code Playgroud)