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?
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
