[英]No DateTime?.ToString(string) overload?
I am aware of the standard procedure for displaying a DateTime
in a custom format, like so: 我知道以自定义格式显示DateTime
的标准过程,如下所示:
MessageBox.Show(dateSent.ToString("dd/MM/yyyy hh:mm:ss"));
However, when I change the variable from a DateTime
to a DateTime?
但是,当我将变量从DateTime
更改为DateTime?
to accept null values, I lose the definition for the ToString(string)
overload. 为了接受空值,我失去了ToString(string)
重载的定义。 I need to use DateTime?
我需要使用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. 当我从一个可能具有空值的数据库中读取时 - 如果数据库中的字段具有空值,那么我也需要为变量赋值空值。
So I have two questions: 所以我有两个问题:
1) Out of curiosity, does anyone know if there is a reason why DateTime?
1)出于好奇,有没有人知道DateTime?
是否有原因DateTime?
does not contain an overload for ToString(string)
? 不包含ToString(string)
的重载?
2) Could anyone suggest an alternative method for what I am trying to achieve? 2)有人可以为我想要实现的目标建议一种替代方法吗?
DateTime?
is syntactic sugar for Nullable<DateTime>
and that's why it don't have ToString(format)
overload. 是Nullable<DateTime>
语法糖,这就是它没有ToString(format)
重载的原因。
However, you can access underlying DateTime
struct using Value
property. 但是,您可以使用Value
属性访问基础DateTime
结构。 But before that use HasValue
to check, if the value exists. 但在此之前使用HasValue
检查,如果值存在。
MessageBox.Show(dateSent.HasValue ? dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") : string.Empty)
Instead of having to manually perform a null check every time, you can write an extension method. 您可以编写扩展方法,而不必每次都手动执行空检查。
public static string ToStringFormat(this DateTime? dt, string format)
{
if(dt.HasValue)
return dt.Value.ToString(format);
else
return "";
}
And use it like this (with whatever string format you want) 并像这样使用它(使用你想要的任何字符串格式)
Console.WriteLine(myNullableDateTime.ToStringFormat("dd/MM/yyyy hh:mm:ss"));
你仍然可以使用
variableName.Value.ToString(customFormat);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.