没有DateTime?.ToString(string)重载?

我知道以自定义格式显示DateTime的标准过程,如下所示:

MessageBox.Show(dateSent.ToString("dd/MM/yyyy hh:mm:ss"));

但是,当我将变量从DateTime更改为DateTime? 接受空值,我失去了ToString(string)重载的定义。 我需要使用DateTime? 当我从一个可能具有空值的数据库中读取时 – 如果数据库中的字段具有空值,那么我也需要为变量赋值空值。

所以我有两个问题:

1)出于好奇,有没有人知道DateTime?是否有原因DateTime? 不包含ToString(string)的重载?

2)有人可以为我想要实现的目标提出另一种方法吗?

DateTime?Nullable语法糖,这就是它没有ToString(format)重载的原因。

但是,您可以使用Value属性访问基础DateTime结构。 但在此之前使用HasValue检查,如果值存在。

 MessageBox.Show(dateSent.HasValue ? dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") : string.Empty) 

您可以编写扩展方法,而不必每次都手动执行空检查。

  public static string ToStringFormat(this DateTime? dt, string format) { if(dt.HasValue) return dt.Value.ToString(format); else return ""; } 

并像这样使用它(使用你想要的任何字符串格式)

  Console.WriteLine(myNullableDateTime.ToStringFormat("dd/MM/yyyy hh:mm:ss")); 

你仍然可以使用

 variableName.Value.ToString(customFormat);