我一直在寻找,但没有找到解决办法。如何处理应该能够包含未初始化值(相当于null)的DateTime ?我有一个类,它可能有一个DateTime属性值设置或没有。我正在考虑将属性持有人初始化为DateTime。MinValue,然后可以很容易地检查。我想这是一个很常见的问题,你是怎么做到的?


当前回答

您可以为此使用一个可空的DateTime。

Nullable<DateTime> myDateTime;

也可以这样写

DateTime? myDateTime;

其他回答

我会考虑使用可空类型。

DateTime吗?myDate而不是DateTime。

问题本身给出了正确的答案。“如果datetime为空,你如何处理它?”,提问者在最后用datetime . minvalue给出答案。我的想法是提问者的方式应该是不变的。我建议使用DateTime。MaxValue比较,因为它不会发生直到12/31/9999。如果为真,则将field显示为日期以外的其他内容。下面是一个例子;

 DateNotified = DBNull.Value.Equals(reader["DateNotified"])? Convert.ToDateTime(reader["DateNotified"]): DateTime.MaxValue

在前端 如果你使用的是网格,那么;

columns.Add(col => col.DateNotified).Css("text-right").Titled("Date Notified").RenderValueAs(c => c.DateNotified.ToString("MM/dd/yyyy").Equals(DateTime.MaxValue) ? "":c.DateNotified.ToString("MM/dd/yyyy"));

或者一个简单的观点

@Model.DateNotified.ToString("MM/dd/yyyy").Equals(DateTime.MaxValue) ? "":Model.DateNotified.ToString("MM/dd/yyyy")

可以使用可空类。

DateTime? date = new DateTime?();

您可以为此使用一个可空的DateTime。

Nullable<DateTime> myDateTime;

也可以这样写

DateTime? myDateTime;

虽然每个人都已经给出了答案,但我将提到一种容易将datetime传递到函数中的方法

[ERROR:cannot convert system.datetime?]system.datetime)

DateTime? dt = null;
DateTime dte = Convert.ToDateTime(dt);

现在你可以在函数内部传递dte了,没有任何问题。