首页 > 解决方案 > 在 Nullable 的情况下如何格式化 DateTime?

问题描述

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

例如

public DateTime BirthDate { get; set; }

在上述代码的情况下,我可以格式化出生日期。

但是在以下代码的情况下,我无法获得.ToString()方法的所有重载。

public DateTime? BirthDate { get; set; }

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

例如

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

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

标签: c#asp.net-mvc

解决方案


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

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

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

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

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

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> 

推荐阅读