Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange .Net datetime issue

Tags:

c#

.net

datetime

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.

like image 826
Jeremy Seekamp Avatar asked Jan 31 '26 00:01

Jeremy Seekamp


2 Answers

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);
like image 198
Nick Craver Avatar answered Feb 02 '26 15:02

Nick Craver


I was unable to reproduce this. In any case this is the preferred way of doing this:

DateTime filterDate = endDate ?? DateTime.Now.AddDays(7);
like image 43
ChaosPandion Avatar answered Feb 02 '26 15:02

ChaosPandion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!