如何将可空的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方法没有重载 一个参数


当前回答

考虑到您实际上想要提供格式,我建议将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   
}

其他回答

这个问题的问题在于,当可为空的datetime没有值时,您没有指定所需的输出。下面的代码将输出DateTime。MinValue在这种情况下,与当前接受的答案不同,将不会抛出异常。

dt2.GetValueOrDefault().ToString(format);

我喜欢这个选项:

Console.WriteLine(dt2?.ToString("yyyy-MM-dd hh:mm:ss") ?? "n/a");

. datetime != null ?((DateTime)s.SendDateTime).ToString("HH:mm:ss"): null

甚至在c# 6.0中有一个更好的解决方案:

DateTime? birthdate;

birthdate?.ToString("dd/MM/yyyy");

最短的回答

$"{dt:yyyy-MM-dd hh:mm:ss}"

测试

DateTime dt1 = DateTime.Now;
Console.Write("Test 1: ");
Console.WriteLine($"{dt1:yyyy-MM-dd hh:mm:ss}"); //works

DateTime? dt2 = DateTime.Now;
Console.Write("Test 2: ");
Console.WriteLine($"{dt2:yyyy-MM-dd hh:mm:ss}"); //Works

DateTime? dt3 = null;
Console.Write("Test 3: ");
Console.WriteLine($"{dt3:yyyy-MM-dd hh:mm:ss}"); //Works - Returns empty string

Output
Test 1: 2017-08-03 12:38:57
Test 2: 2017-08-03 12:38:57
Test 3: