Get short date for System Nullable datetime (datetime ?) in C#
You need to use .Value
first (Since it's nullable).
var shortString = yourDate.Value.ToShortDateString();
But also check that yourDate
has a value:
if (yourDate.HasValue) {
var shortString = yourDate.Value.ToShortDateString();
}
string.Format("{0:d}", dt);
works:
DateTime? dt = (DateTime?)DateTime.Now;
string dateToday = string.Format("{0:d}", dt);
Demo
If the DateTime?
is null
this returns an empty string.
Note that the "d" custom format specifier is identical to ToShortDateString
.
That function is absolutely available within the DateTime
class. Please refer to the MSDN documentation for the class: http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx
Since Nullable
is a generic on top of the DateTime
class you will need to use the .Value
property of the DateTime?
instance to call the underlying class methods as seen below:
DateTime? date;
String shortDateString;
shortDateString = date.Value.ToShortDateString();
Just be aware that if you attempt this while date
is null an exception will be thrown.