iOS – 如何比较两次?

我使用下面的函数来检查消息是否已经过期 –

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

如果我比较两个不同的date,这工作正常。 但是,如果邮件在今天早些时候过期,它将返回false。 任何想法如何我可以解决它?

(添加我的评论作为答案:)

这不应该发生, NSDate实例之间1秒的差异也是足够的。 添加两个date的NSLog() ,看看他们是否确实不同。

您可以使用NSDate类的系统方法与当前时间进行比较

 - (NSTimeInterval)timeIntervalSinceNow 

返回值是接收者与当前date和时间之间的间隔。 如果接收者比当前date和时间早,则返回值是负值。

所以正确的代码将是

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

或者如果你想比较两个date,使用

 - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate 
 +(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; } } 

检查当天是否返回NSOrderedSame。 也许你需要分别比较时间。