您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用ToString()格式化可为空的DateTime?

如何使用ToString()格式化可为空的DateTime?

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")
其他 2022/1/1 18:17:32 有437人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶