c# - 在 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# 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>
推荐阅读
- python - 获取由熊猫中另一列排序的列划分的第一个匹配项
- asp.net-mvc - ASP.net core 3.1 中控制器和剃须刀页面之间的路由
- mysql - 当多条记录同时插入时,如何避免重复的序号?
- javascript - 全局覆盖默认类型属性
- python - 如果输入不在域中,则使 matplotlib 不绘图
- python - 无法使用 blit 在 pygame 中显示图像
- android - Android Navigation 从第一个片段中删除工具栏
- python - Python:从 a-Tag 获取下载链接,其中包含 onclick 生成的链接
- google-sheets - 如何使用两个条件对范围中的值进行求和,同时在 Google 表格中使用 OR 条件
- vba - 我的拆分访问数据库为其他用户进行查询更改