简体   繁体   中英

C# Nullable<DateTime> to string

I have a 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 ?

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. Just call ToString on your value; 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:

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>

nullNullable<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() . It handles Nullable<T> object for null value.

Here is the source of .NET Framework for 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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM