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

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

问题描述

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

  DateTime dt = DateTime.Now; 
Console.WriteLine(dt.ToString(yyyy-MM-dd hh:mm:ss)); //工作

DateTime? dt2 = DateTime.Now;
Console.WriteLine(dt2.ToString(yyyy-MM-dd hh:mm:ss)); //给出以下错误:




无法重载方法ToString需要
一个参数



解决方案

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

编辑:如其他注释中所述,检查是否存在非空值。 >

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.

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

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