Get short date for System Nullable datetime (datetime ?) in C#

被刻印的时光 ゝ 提交于 2019-11-30 06:51:00

问题


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.


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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.




回答5:


Check if it has value, then get required date

if (nullDate.HasValue)
{
     nullDate.Value.ToShortDateString();
}



回答6:


Try

    if (nullDate.HasValue)
    {
         nullDate.Value.ToShortDateString();
    }



回答7:


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.



来源:https://stackoverflow.com/questions/18982303/get-short-date-for-system-nullable-datetime-datetime-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!