4

I use the following function to check if a message has expired -

- (BOOL) hasExpired:(NSDate*)myDate
{     
    if(myDate == nil)
    {
        return false;
    }
    NSDate *now = [NSDate date];
    return !([now compare:myDate] == NSOrderedAscending);
}

This works fine if I am comparing two different dates. However, it returns false if the message has expired earlier in the day today. Any ideas on how I might fix it?

WrightsCS
  • 50,551
  • 22
  • 134
  • 186
Suchi
  • 9,989
  • 23
  • 68
  • 112
  • 1
    This should not happen, also 1 second difference between NSDate instances is enough. Add an `NSLog()` with both dates there to see whether they are indeed different. – Pascal Dec 21 '11 at 20:12
  • You were right. If you turn it into an answer I could accept it. – Suchi Jan 03 '12 at 17:22

4 Answers4

2

You can use system method of NSDate class to compare with current time

- (NSTimeInterval)timeIntervalSinceNow

Return value is the interval between the receiver and the current date and time. If the receiver is earlier than the current date and time, the return value is negative.

So correct code will be

- (BOOL) hasExpired:(NSDate*)myDate 
{
    return [myDate timeIntervalSinceNow] < 0.f;
}

Or if you want to compare 2 dates, use

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
Nikita Ivaniushchenko
  • 1,425
  • 11
  • 11
2

(Adding my comment as an answer:)

This should not happen, also 1 second difference between NSDate instances is enough. Add an NSLog() with both dates there to see whether they are different indeed.

Pascal
  • 16,846
  • 4
  • 60
  • 69
1
+(BOOL)isEndDateBigger :(NSDate *)currDate :(NSDate *)endDate {
     if ([currDate compare:endDate] == NSOrderedDescending) {
     NSLog(@"date1 is later than date2");
     return YES; 
     } else if ([currDate compare:endDate] == NSOrderedAscending) {
     return NO;
     } else {
     return NO;
   }
}
Gajendra K Chauhan
  • 3,387
  • 7
  • 40
  • 55
Nits007ak
  • 743
  • 7
  • 15
0

Check to see if it is returning NSOrderedSame when it is the same day. Maybe you need to compare the time as well, separately.

bweberapps
  • 86
  • 3