C#Nullable <DateTime>转换为字符串

C# Nullable<DateTime> to string

我有一个DateTime?变量,有时值是null,当值是null时我如何返回一个空字符串"",或者当不是null时如何返回DateTime值? >


尽管许多答案是正确的,但所有答案都不必要地复杂。如果该值在逻辑上为空,则在可为空的DateTime上调用ToString的结果已经是一个空字符串。只需按您的值调用ToString即可;它会完全满足您的要求。


1
string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;


实际上,这是Nullable类型的默认行为,如果没有值,它们将不返回任何内容:

1
2
3
4
5
6
7
8
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());
    }
}

这产生了

1
2
<>
<2009-09-18 19:16:09>


nullNullable<T>上调用.ToString()将返回一个空字符串。


您可以编写扩展方法

1
2
3
4
5
6
public static string ToStringSafe(this DateTime? t) {
  return t.HasValue ? t.Value.ToString() : String.Empty;
}

...
var str = myVariable.ToStringSafe();


您需要做的只是简单地调用.ToString()。它为null值处理Nullable<T>对象。

以下是Nullable<T>.ToString()的.NET Framework的来源:

1
2
3
public override string ToString() {
    return hasValue ? value.ToString() :"";
}

1
2
3
DateTime? d;
// stuff manipulating d;
return d != null ? d.Value.ToString() : String.Empty;

1
2
DateTime d?;
string s = d.HasValue ? d.ToString() : string.Empty;

1
2
3
4
if (aDate.HasValue)
    return aDate;
else
    return string.Empty;

1
2
3
4
5
6
7
DateTime? MyNullableDT;
....
if (MyNullableDT.HasValue)
{
    return MyNullableDT.Value.ToString();
}
return"";

根据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.