如何将可空的DateTime dt2转换为格式化的字符串?

DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss")); //works

DateTime? dt2 = DateTime.Now;
Console.WriteLine(dt2.ToString("yyyy-MM-dd hh:mm:ss")); //gives following error:

ToString方法没有重载 一个参数


当前回答

我认为你必须使用getvalueordefault - method。如果实例为空,则不定义ToString("yy…")的行为。

dt2.GetValueOrDefault().ToString("yyy...");

其他回答

像这样简单的事情怎么样:

String.Format("{0:dd/MM/yyyy}", d2)

也许这是一个迟来的答案,但可能对其他人有所帮助。

简单的是:

nullabledatevariable.Value.Date.ToString("d")

或者用其他格式代替d。

Best

剃须刀的语法:

@(myNullableDateTime?.ToString("yyyy-MM-dd") ?? String.Empty)

考虑到您实际上想要提供格式,我建议将IFormattable接口添加到Smalls扩展方法中,这样您就不会有讨厌的字符串格式连接。

public static string ToString<T>(this T? variable, string format, string nullValue = null)
where T: struct, IFormattable
{
  return (variable.HasValue) 
         ? variable.Value.ToString(format, null) 
         : nullValue;          //variable was null so return this value instead   
}

您可以使用dt2. value . tostring ("format"),但当然这需要dt2 != null,这首先就否定了可空类型的使用。

这里有几个解决方案,但最大的问题是:您希望如何格式化空日期?