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


当前回答

我总是把时间设置为DateTime.MinValue。这样我就不会得到任何NullErrorException,我可以将它与我知道没有设置的日期进行比较。

其他回答

我总是把时间设置为DateTime.MinValue。这样我就不会得到任何NullErrorException,我可以将它与我知道没有设置的日期进行比较。

DateTime ?MyDateTime{拿套;}

MyDateTime = (dr["f1"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr["f1"]);

问题本身给出了正确的答案。“如果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传递到函数中的方法

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

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

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

如果你使用。net 2.0(或更高版本),你可以使用可空类型:

DateTime? dt = null;

or

Nullable<DateTime> dt = null;

之后:

dt = new DateTime();

你可以用:

if (dt.HasValue)
{
  // Do something with dt.Value
}

或者你可以这样用:

DateTime dt2 = dt ?? DateTime.MinValue;

你可以在这里阅读更多: http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx