JL.
JL.

Reputation: 81292

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?

Upvotes: 37

Views: 33523

Answers (12)

Gongxi
Gongxi

Reputation: 162

As Eric Lippert's answer. I think this will This code should meet the requirements.

Nullable<DateTime> nullableDatetime = null;
string? datetimeString = nullableDatetime.ToString();
string nullableString = datetimeString ?? string.Empty;

Upvotes: 0

David Zhang
David Zhang

Reputation: 39

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.

Upvotes: 0

Jalal
Jalal

Reputation: 6836

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() : "";
}

Upvotes: 3

DJ.
DJ.

Reputation: 1025

Calling .ToString() on a Nullable<T> that is null will return an empty string.

Upvotes: 8

Mike
Mike

Reputation: 5509

if (aDate.HasValue)
    return aDate;
else
    return string.Empty;

Upvotes: 1

Ahmed Khalaf
Ahmed Khalaf

Reputation: 1220

DateTime? MyNullableDT;
....
if (MyNullableDT.HasValue)
{
    return MyNullableDT.Value.ToString();
}
return "";

Upvotes: 1

Jon Seigel
Jon Seigel

Reputation: 12401

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

Upvotes: 43

Eric Lippert
Eric Lippert

Reputation: 660128

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.

Upvotes: 113

Joey
Joey

Reputation: 354556

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>

Upvotes: 18

JaredPar
JaredPar

Reputation: 754763

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();

Upvotes: 7

Patrick Desjardins
Patrick Desjardins

Reputation: 140823

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

Upvotes: 1

Cecil Has a Name
Cecil Has a Name

Reputation: 4992

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

Upvotes: 2

Related Questions