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

14

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

问题描述

限时送ChatGPT账号..

如何将可为空的 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14