Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: problem with NSOrderedDescending and NSOrderedAscending

I want to compare dates and I use this code

in one example date values for my date are: date1 = 6/06/2011 date2 = 8/06/2011

if dateSelected = 7/06/2011 it's all ok, but if dateSelected = 6/06/2011 or dateSelected = 8/06/2011 the code don't entry inside my "if", why???

if (([dateSelected compare:date1] == NSOrderedDescending) &&
                ([dateSelected compare:date2]== NSOrderedAscending))
            {}
like image 398
cyclingIsBetter Avatar asked Jan 28 '26 22:01

cyclingIsBetter


1 Answers

NSDates represent a point in time since 1/1/2000 00:00 UTC. So all of those dates have time components. -compare: compares date and time.

Presumably, you really want to check if the date selected is between 6/6/2011 00:00 and 9/6/2011 00:00. Also you probably want the date 6/6/2011 00:00 to count as in the range. So you need something like

NSComparisonResult compareStart = [date1 compare: selectedDate]; // date1 is 6/6/2011 00:00
NSComparisonResult compareEnd = [date2 compare: selectedDate];   // date2 is 9/6/2011 00:00

if ((compareStart == NSOrderedAscending) || (compareStart == NSOrderedSame)
    && (compareEnd == NSOrderedDescending))
{
    // date is in the right range
}
like image 117
JeremyP Avatar answered Jan 30 '26 13:01

JeremyP



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!