iOS - 如何比较两次?

时间:2011-12-21 19:58:55

标签: ios nsdate

我使用以下函数检查邮件是否已过期 -

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

如果我比较两个不同的日期,这可以正常工作。但是,如果消息在当天早些时候已过期,则返回false。关于如何修复它的任何想法?

4 个答案:

答案 0 :(得分:2)

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

- (NSTimeInterval)timeIntervalSinceNow

返回值是接收者与当前日期和时间之间的间隔。如果接收者早于当前日期和时间,则返回值为负。

所以正确的代码将是

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

或者如果您想比较2个日期,请使用

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

答案 1 :(得分:2)

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

这不应该发生,NSDate个实例之间的1秒差异就足够了。添加NSLog(),其中包含两个日期,以确定它们是否确实不同。

答案 2 :(得分: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;
   }
}

答案 3 :(得分:0)

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

相关问题