简体   繁体   中英

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. Why is this?

In the first example filterDate ends up with a value of 01/01/0001. In the second example I get the expected result which is filterDate is a datetime 7 days in the future.

EDIT: At this point I've even tried setting endDate = null just to make sure and here is a screen shot of what happens. 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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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