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 =开发者_如何学C 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);
精彩评论