Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date comparison with MaxValue not working

Tags:

c#

datetime

I have a nullable Date property called BoughtDate. I am trying the following:

if( item.BoughtDate.Value.Equals( DateTime.MaxValue) ) item.BoughtDate= null;

also tried this:

if( item.BoughtDate.Equals( DateTime.MaxValue) ) item.BoughtDate=null;

When debugging, my BoughtDate and DateTime.MaxValue seems exactly the same - yet it says it is not the same(does not set my item.BoughtDate to null)

Why does my comparison not work?

like image 578
user1702369 Avatar asked Jun 02 '17 08:06

user1702369


1 Answers

The problem,as @PaulSuart points in the comments, is probably the milliseconds precision. DateTime.MaxValue.TimeOfDay is {23:59:59.9999999},but your BoughtDate.TimeOfDay is probably {23:59:59.9990000},so they are not equal.

What i would do is just comparing the dates, i think that's enough in most cases:

if( item.BoughtDate.Value.Date.Equals( DateTime.MaxValue.Date) ) item.BoughtDate= null;
like image 93
5 revs, 4 users 77%SuperG Avatar answered Oct 13 '22 20:10

5 revs, 4 users 77%SuperG