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?


基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01