首页 > 解决方案 > 在 C# 中格式化可为空的 DateTime

问题描述

我试图从DateTime可以为空的对象中仅获取日期部分。我试过这个东西

string dueDate = siteRow.DueDate.ToString(cultureInfo.DateTimeFormat.ShortDatePattern)

但它会引发错误:

错误 CS1501 方法“ToString”没有重载需要 1 个参数

上面siteRow.DueDate是一个 DateTime 对象。我无法弄清楚正确的语法。请帮我解决这个问题。

标签: c#

解决方案


Nullable<T>是包装 T 类型的通用包装器

它有 2 个属性:Value 和 HasValue。Value 是包装对象的值,HasValue 是一个布尔值,指示在 Value 属性中是否有要获取的值。如果 HasValue 为 true,则 Value 将不是默认值(通常为 null 或空结构)。如果 HasValue 为 false,则 Value 将是默认值。

因此,要访问 DateTime 的 ToString 方法,您需要调用DueDate.Value.ToString

将会

var dueDate = siteRow.DueDate.HasValue ? siteRow.DueDate.Value.ToString(cultureInfo.DateTimeFormat.ShortDatePattern) : null

或使用缩写语法

var dueDate = siteRow.DueDate?.ToString(cultureInfo.DateTimeFormat.ShortDatePattern);

推荐阅读