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.
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.
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();
}
yourDate.HasValue
first. –
Adena string.Format("{0:d}", dt);
works:
DateTime? dt = (DateTime?)DateTime.Now;
string dateToday = string.Format("{0:d}", dt);
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.
DateTime != DateTime?
(Nullable<DateTime>
). –
Adena If you want to be guaranteed to have a value to display, you can use GetValueOrDefault()
in conjunction with the ToShortDateString
method that other postelike this:
yourDate.GetValueOrDefault().ToShortDateString();
This will show 01/01/0001 if the value happened to be null.
A more concise way to do the same thing would be this:
var shortString = yourDate?.ToShortDateString();
It returns a null if it is a null and the short date if it is not null.
Check if it has value, then get required date
if (nullDate.HasValue)
{
nullDate.Value.ToShortDateString();
}
Try
if (nullDate.HasValue)
{
nullDate.Value.ToShortDateString();
}
If you are using .cshtml then you can use as
<td>@(item.InvoiceDate==null?"":DateTime.Parse(item.YourDate.ToString()).ToShortDateString())</td>
or if you try to find short date in action or method in c# then
yourDate.GetValueOrDefault().ToShortDateString();
And is already answered above by Steve.
I have shared this as i used in my project. it works fine. Thank you.
© 2022 - 2024 — McMap. All rights reserved.
.Value
method ofSystem.Nullable
Take a look at my answer for further reference. – Kristoforo