开发者

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜