我如何格式化的ToString可空的日期时间()? [英] How can I format a nullable DateTime with ToString()?

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

问题描述

我如何转换可空的DateTime DT2 以格式化字符串?

  DateTime的DT = DateTime.Now;
Console.WriteLine(dt.ToString(YYYY-MM-DD HH:MM:SS)); //作品约会时间? 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:!?毫米: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可空的日期时间()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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