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


当前回答

如果你使用。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

其他回答

我有同样的问题,因为我必须给Null作为DateTime的参数,同时执行单元测试抛出ArgumentNullException。它在我的情况下工作,使用以下选项:

Assert.Throws<ArgumentNullException>(()=>sut.StartingDate = DateTime.Parse(null));

值得指出的是,虽然DateTime变量不能为空,但它仍然可以被比较为空而不会出现编译器错误:

DateTime date;
...
if(date == null) // <-- will never be 'true'
  ...

问题本身给出了正确的答案。“如果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设置为Nullable。默认情况下DateTime不是空的。有几种方法可以使它为空。在类型DateTime后使用问号?myTime或使用泛型样式Nullable。

DateTime? nullDate = null;

or

DateTime? nullDate;

如果你使用。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