C# Nullable<DateTime> to string
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>