Reputation: 679
I searched this question before and found:
if (([dateToCompare compare:4HoursEarlier] == NSOrderedAscending) && ([dateToCompare compare:specifiedDate] == NSOrderedDescending))
{
NSLog(@"dateToCompare between 4HoursEarlier and specifiedDate");
// do something
}
Unfortunately, this seems not to work (the NSLog never gets printed).
I have a for loop that goes through an array (which contains dates). I need to check if the specified date is within 4 hours of another date. I have (pseudocode):
specifiedDate = a date I specify;
dateToCompare = current date gathered in for loop;
4HoursEarlier = 4 hours before specifiedDate;
How can I check if a specifiedDate is within 4 hours of dateToCompare (a date gathered from an array/for loop)?
Upvotes: 0
Views: 598
Reputation: 540145
I think you got the comparisons the wrong way around. Exchange NSOrderedAscending
and NSOrderedDescending
in your condition.
My memory aid is
[obj1 compare:obj2] == NSOrderedAscending : obj1, obj2 is an ascending sequence
[obj1 compare:obj2] == NSOrderedDescending : obj1, obj2 is an descending sequence
Therefore, to check if dateToCompare
is later in time than fourHoursEarlier
, you have
to use
if ([dateToCompare compare:fourHoursEarlier] == NSOrderedDescending) ...
Upvotes: 1