IOS: problem with NSOrderedDescending and NSOrderedAscending

ぃ、小莉子 提交于 2020-01-02 07:36:30

问题


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))
            {}

回答1:


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
}



回答2:


Try this:

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



回答3:


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);


来源:https://stackoverflow.com/questions/6249196/ios-problem-with-nsordereddescending-and-nsorderedascending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!