[英]C# Nullable<DateTime> to string
I have a DateTime?
我有一个
DateTime?
variable, sometimes the value is null
, how can I return an empty string ""
when the value is null
or the DateTime
value when not null
? 变量,有时值为
null
,我怎么能返回一个空字符串""
,如果值是null
或DateTime
值时,没有null
?
Though many of these answers are correct, all of them are needlessly complex. 尽管许多答案都是正确的,但所有答案都不必要地复杂。 The result of calling ToString on a nullable DateTime is already an empty string if the value is logically null.
如果该值在逻辑上为空,则在可为空的DateTime上调用ToString的结果已经是一个空字符串。 Just call ToString on your value;
只需按您的值调用ToString即可; it will do exactly what you want.
它会完全按照您的要求进行。
string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;
Actually, this is the default behaviour for Nullable types, that without a value they return nothing: 实际上,这是Nullable类型的默认行为,没有值则它们不返回任何值:
public class Test {
public static void Main() {
System.DateTime? dt = null;
System.Console.WriteLine("<{0}>", dt.ToString());
dt = System.DateTime.Now;
System.Console.WriteLine("<{0}>", dt.ToString());
}
}
this yields 这产生
<>
<2009-09-18 19:16:09>
在null
的Nullable<T>
上调用.ToString()
将返回一个空字符串。
You could write an extension method 你可以写一个扩展方法
public static string ToStringSafe(this DateTime? t) {
return t.HasValue ? t.Value.ToString() : String.Empty;
}
...
var str = myVariable.ToStringSafe();
All you need to do is to just simply call .ToString()
. 您只需要简单地调用
.ToString()
。 It handles Nullable<T>
object for null
value. 它为
null
值处理Nullable<T>
对象。
Here is the source of .NET Framework for Nullable<T>.ToString()
: 这是.NET Framework的
Nullable<T>.ToString()
:
public override string ToString() {
return hasValue ? value.ToString() : "";
}
DateTime? d;
// stuff manipulating d;
return d != null ? d.Value.ToString() : String.Empty;
DateTime? MyNullableDT;
....
if (MyNullableDT.HasValue)
{
return MyNullableDT.Value.ToString();
}
return "";
if (aDate.HasValue)
return aDate;
else
return string.Empty;
DateTime d?;
string s = d.HasValue ? d.ToString() : string.Empty;
According to Microsoft's documentation : 根据Microsoft的文档 :
The text representation of the value of the current Nullable object if the HasValue property is true, or an empty string ("") if the HasValue property is false.
如果HasValue属性为true,则为当前Nullable对象的值的文本表示形式;如果HasValue属性为false,则为空字符串(“”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.