Suchi
Suchi

Reputation: 10039

iOS - how to compare two times?

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?

Upvotes: 4

Views: 5743

Answers (4)

Nits007ak
Nits007ak

Reputation: 753

+(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;
   }
}

Upvotes: 1

Pascal
Pascal

Reputation: 16941

(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.

Upvotes: 2

Nikita Ivaniushchenko
Nikita Ivaniushchenko

Reputation: 1435

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

Upvotes: 2

bweberapps
bweberapps

Reputation: 86

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

Upvotes: 0

Related Questions