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


当前回答

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

编辑:如其他注释中所述,检查是否有一个非空值。

更新:如评论中推荐,扩展方法:

public static string ToString(this DateTime? dt, string format)
    => dt == null ? "n/a" : ((DateTime)dt).ToString(format);

从c# 6开始,您可以使用空条件操作符来进一步简化代码。如果DateTime?是零。

dt2?.ToString("yyyy-MM-dd hh:mm:ss")

其他回答

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

编辑:如其他注释中所述,检查是否有一个非空值。

更新:如评论中推荐,扩展方法:

public static string ToString(this DateTime? dt, string format)
    => dt == null ? "n/a" : ((DateTime)dt).ToString(format);

从c# 6开始,您可以使用空条件操作符来进一步简化代码。如果DateTime?是零。

dt2?.ToString("yyyy-MM-dd hh:mm:ss")

简单的通用扩展

public static class Extensions
{

    /// <summary>
    /// Generic method for format nullable values
    /// </summary>
    /// <returns>Formated value or defaultValue</returns>
    public static string ToString<T>(this Nullable<T> nullable, string format, string defaultValue = null) where T : struct
    {
        if (nullable.HasValue)
        {
            return String.Format("{0:" + format + "}", nullable.Value);
        }

        return defaultValue;
    }
}

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

最短的回答

$"{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: 

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

DateTime? birthdate;

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