如何获取短日期 获取短日期
System Nullable datetime (datetime ?)
for ed
12/31/2013 12:00:00
--> 只应返回 12/31/2013
。
我没有看到可用的
ToShortDateString
。
您需要首先使用
.Value
(因为它可以为空)。
var shortString = yourDate.Value.ToShortDateString();
但还要检查
yourDate
是否具有值:
if (yourDate.HasValue) {
var shortString = yourDate.Value.ToShortDateString();
}
string.Format("{0:d}", dt);
有效:
DateTime? dt = (DateTime?)DateTime.Now;
string dateToday = string.Format("{0:d}", dt);
如果
DateTime?
是 null
,则返回空字符串。
请注意,“d”自定义格式说明符与
ToShortDateString
相同。
该功能在
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 时尝试执行此操作,将会抛出异常。
如果你想保证有一个值可以显示,你可以将
GetValueOrDefault()
与其他帖子类似的 ToShortDateString
方法结合使用:
yourDate.GetValueOrDefault().ToShortDateString();
如果该值恰好为空,则会显示 01/01/0001。
检查是否有价值,然后获取所需日期
if (nullDate.HasValue)
{
nullDate.Value.ToShortDateString();
}
尝试
if (nullDate.HasValue)
{
nullDate.Value.ToShortDateString();
}
如果您使用 .cshtml 那么您可以使用 as
<td>@(item.InvoiceDate==null?"":DateTime.Parse(item.YourDate.ToString()).ToShortDateString())</td>
或者如果您尝试在 c# 中的操作或方法中查找短日期,那么
yourDate.GetValueOrDefault().ToShortDateString();
史蒂夫已经在上面回答了。
我已经分享了我在项目中使用的内容。效果很好。谢谢你。
执行相同操作的更简洁方法是
yourDate?.Date
,如果为空,则返回空,如果不为空,则返回短日期。