如何使用 ToString() 格式化可为空的 DateTime? [英] How can I format a nullable DateTime with ToString()?

查看:41
本文介绍了如何使用 ToString() 格式化可为空的 DateTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

DateTime dt = DateTime.Now;Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));//作品约会时间?dt2 = 日期时间.现在;Console.WriteLine(dt2.ToString("yyyy-MM-dd hh:mm:ss"));//给出以下错误:

<块引用>

ToString 方法没有重载一个论点

解决方案

Console.WriteLine(dt2 != null ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "不适用");

如其他评论中所述,检查是否存在非空值.

更新:按照评论中的建议,扩展方法:

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

从 C# 6 开始,您可以使用 空条件运算符 进一步简化代码.如果 DateTime? 为 null,则下面的表达式将返回 null.

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

How can I convert the nullable DateTime dt2 to a formatted string?

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:

no overload to method ToString takes one argument

解决方案

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

EDIT: As stated in other comments, check that there is a non-null value.

Update: as recommended in the comments, extension method:

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

And starting in C# 6, you can use the null-conditional operator to simplify the code even more. The expression below will return null if the DateTime? is null.

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

这篇关于如何使用 ToString() 格式化可为空的 DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆