How to get short date for Get short date for System Nullable datetime (datetime ?)
for ed 12/31/2013 12:00:00
--> only should return 12/31/2013
.
I don't see the ToShortDateString
available.
The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.
ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.
DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.
To clarify the answer's "finally" a bit - the default of Nullable<DateTime> (DateTime?) is null, because Nullable<T> creates a reference type.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With