在 C# 中获取系统可空日期时间(日期时间?)的短日期

问题描述 投票:0回答:8

如何获取短日期 获取短日期

System Nullable datetime (datetime ?)

for ed

12/31/2013 12:00:00
--> 只应返回
12/31/2013

我没有看到可用的

ToShortDateString

c# .net string datetime nullable
8个回答
117
投票

您需要首先使用

.Value
(因为它可以为空)。

var shortString = yourDate.Value.ToShortDateString();

但还要检查

yourDate
是否具有值:

if (yourDate.HasValue) {
   var shortString = yourDate.Value.ToShortDateString();
}

22
投票

string.Format("{0:d}", dt);
有效:

DateTime? dt = (DateTime?)DateTime.Now;
string dateToday = string.Format("{0:d}", dt);

演示

如果

DateTime?
null
,则返回空字符串。

请注意,“d”自定义格式说明符

ToShortDateString
相同。


8
投票

该功能在

DateTime
类中绝对可用。请参阅该类的 MSDN 文档:http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx

由于

Nullable
DateTime
类之上的泛型,因此您需要使用
.Value
实例的
DateTime?
属性来调用底层类方法,如下所示:

DateTime? date;
String shortDateString;
shortDateString = date.Value.ToShortDateString();

请注意,如果您在

date
为 null 时尝试执行此操作,将会抛出异常。


6
投票

如果你想保证有一个值可以显示,你可以将

GetValueOrDefault()
与其他帖子类似的
ToShortDateString
方法结合使用:

yourDate.GetValueOrDefault().ToShortDateString();

如果该值恰好为空,则会显示 01/01/0001。


1
投票

检查是否有价值,然后获取所需日期

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

1
投票

尝试

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

0
投票

如果您使用 .cshtml 那么您可以使用 as

<td>@(item.InvoiceDate==null?"":DateTime.Parse(item.YourDate.ToString()).ToShortDateString())</td>

或者如果您尝试在 c# 中的操作或方法中查找短日期,那么

yourDate.GetValueOrDefault().ToShortDateString();

史蒂夫已经在上面回答了。

我已经分享了我在项目中使用的内容。效果很好。谢谢你。


0
投票

执行相同操作的更简洁方法是

yourDate?.Date
,如果为空,则返回空,如果不为空,则返回短日期。

© www.soinside.com 2019 - 2024. All rights reserved.