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开始,您可以使用空条件运算符来进一步简化代码。如果the DateTime?
为null ,则下面的表达式将返回null。
dt2?.ToString("yyyy-MM-dd hh:mm:ss")