简体   繁体   English

奇怪的.Net日期时间问题

[英]Strange .Net datetime issue

Setting with a ternary 设置三元组

DateTime filterDate = endDate.HasValue ? endDate.Value : DateTime.Now.AddDays(7);

Non ternary 非三元

DateTime filterDate;
if (endDate.HasValue)
    filterDate = endDate.Value;
else
    filterDate = DateTime.Now.AddDays(7);

If you debug these two statements the value of filterDate will not be the same. 如果调试这两个语句,filterDate的值将不相同。 Why is this? 为什么是这样?

In the first example filterDate ends up with a value of 01/01/0001. 在第一个示例中,filterDate的最终值为01/01/0001。 In the second example I get the expected result which is filterDate is a datetime 7 days in the future. 在第二个例子中,我得到了预期的结果,即filterDate是未来7天的日期时间。

EDIT: At this point I've even tried setting endDate = null just to make sure and here is a screen shot of what happens. 编辑:此时我甚至尝试设置endDate = null只是为了确保,这是一个屏幕截图显示发生了什么。 alt text http://www.freeimagehosting.net/uploads/57bef2e50a.png alt text http://www.freeimagehosting.net/uploads/57bef2e50a.png

Strangest thing I've ever seen. 我见过的最奇怪的事情。

It looks like endDate is being initialized to DateTime.MinValue, can you show the code where you declare endDate? 看起来endDate正在初始化为DateTime.MinValue,你能显示你声明endDate的代码吗?

Also, an even shorter way: 还有一个更短的方式:

DateTime filterDate = endDate ?? DateTime.Now.AddDays(7);

I was unable to reproduce this. 我无法重现这一点。 In any case this is the preferred way of doing this: 在任何情况下,这是这样做的首选方式:

DateTime filterDate = endDate ?? DateTime.Now.AddDays(7);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM