IOS - how to compare twice?

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 great if I compare two different dates. However, it returns false if the message expired earlier in the day today. Any ideas on how I can fix this?

+4
source share
4 answers

(Adding a comment as an answer :)

This should not be, there is also enough 1 second difference between instances of NSDate . Add NSLog() with two dates to see if they are really different.

+2
source

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

 - (NSTimeInterval)timeIntervalSinceNow 

The 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 the 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 
+2
source
 +(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; } } 
+1
source

Check if it returns an NSOrderedSame when it is on the same day. You may also need to compare the time separately.

0
source

Source: https://habr.com/ru/post/1387455/


All Articles