在 C# 中获取系统可为空的日期时间(日期时间?)的短日期
本文关键字:日期 时间 获取 系统 | 更新日期: 2023-09-27 18:32:40
如何获取System Nullable datetime (datetime ?)
的短期约会
对于 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
类之上的泛型,因此您需要使用 DateTime?
实例的 .Value
属性来调用基础类方法,如下所示:
DateTime? date;
String shortDateString;
shortDateString = date.Value.ToShortDateString();
请注意,如果您在 date
为 null 时尝试此操作,则会引发异常。
如果你想保证有一个值要显示,你可以将GetValueOrDefault()
与其他帖子的ToShortDateString
方法结合使用:
yourDate.GetValueOrDefault().ToShortDateString();
如果值恰好为 null,这将显示 01/01/0001。
检查它是否有值,然后获取所需的日期
if (nullDate.HasValue)
{
nullDate.Value.ToShortDateString();
}
尝试
if (nullDate.HasValue)
{
nullDate.Value.ToShortDateString();
}
如果您使用的是 .cshtml,则可以使用
<td>@(item.InvoiceDate==null?"":DateTime.Parse(item.YourDate.ToString()).ToShortDateString())</td>
或者,如果您尝试在 C# 中查找操作或方法中的短日期,则
yourDate.GetValueOrDefault().ToShortDateString();
史蒂夫已经在上面回答了。
我在项目中使用时分享了这个。 它工作正常。谢谢。