How can I format a nullable DateTime with ToString()?(如何使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 ToString() 格式化可为空的 DateTime?
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 使用 rss + c# 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
