没有DateTime?.ToString(string)重载? [英] No DateTime?.ToString(string) overload?

查看:112
本文介绍了没有DateTime?.ToString(string)重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以自定义格式显示 DateTime 的标准过程,如下所示:

I am aware of the standard procedure for displaying a DateTime in a custom format, like so:

MessageBox.Show(dateSent.ToString(dd / MM / yyyy hh:mm:ss));

但是,当我将变量从 DateTime 更改为 DateTime?以接受空值时,我失去了定义对于 ToString(string)重载。我需要使用 DateTime?,因为我正在从一个可能具有空值的数据库读取 - 如果数据库中的字段具有空值,那么我需要分配变量一个空值。

However, when I change the variable from a DateTime to a DateTime? to accept null values, I lose the definition for the ToString(string) overload. I need to use DateTime? as I am reading from a database which potentially has null values - if the field in the database has a null value, then I need to assign the variable a null value too.

所以我有两个问题:

1)出于好奇,有没有人知道如果有一个原因为什么 DateTime?不包含 ToString(string)

1) Out of curiosity, does anyone know if there is a reason why DateTime? does not contain an overload for ToString(string)?

2)有没有人可以为我想要实现的方案提出一种替代方法?

2) Could anyone suggest an alternative method for what I am trying to achieve?

推荐答案

DateTime? <$ c $的语法糖c> Nullable< DateTime> ,这就是为什么它没有 ToString(格式)重载。

但是,您可以使用 Value 属性访问底层 DateTime struct。但是之前使用 HasValue 来检查,如果该值存在。

However, you can access underlying DateTime struct using Value property. But before that use HasValue to check, if the value exists.

MessageBox.Show(dateSent.HasValue ? dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") : string.Empty)

这篇关于没有DateTime?.ToString(string)重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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