IOS: problem with NSOrderedDescending and NSOrderedAscending

落爺英雄遲暮 提交于 2019-12-05 21:06:16

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
}

Try this:

if (([date1 compare:dateSelected] == NSOrderedAscending) &&
                ([date2 compare:dateSelected]== NSOrderedDescending))
            {}

For those who have the same problem than @blackguardian :

Cannot initialize a parameter of type 'NSNumber *' with an lvalue of type 'NSDate *'


On something like this:

NSDate* oldDate = [NSDate date];
BOOL older = ([[NSDate date] compare:oldDate] == NSOrderedDescending);


I do not know why, but you need to cast the "[NSDate date]" into "NSDate*". This is working:

NSDate* oldDate = [NSDate date];
BOOL older = ([[(NSDate*)[NSDate date] compare:oldDate] == NSOrderedDescending);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!