iPhone - 比较日期不按预期工作

时间:2011-08-20 17:37:26

标签: iphone objective-c ios nsdate

我有一个设置为特定日期的事件。我想检查日期是否在当前日期的5分钟范围内。例如:如果事件设置为晚上9:10,现在是晚上9:02。我想看看当前时间是否在9:05到9:15之间。

所以,我做......

NSDate *currentDate ... this variable contains the current date
NSDate *plusFive = [eventDate dateByAddingTimeInterval:300];
NSDate *minusFive = [eventDate dateByAddingTimeInterval:-300];

NSComparisonResult result1 = [eventDate compare:minusFive];
NSComparisonResult result2 = [eventDate compare:plusFive];


if ( (result1 == NSOrderedAscending) && (result2 == NSOrderedDescending) ) { 
    // if the current date is not inside the 5 minutes window
    // or in other words, if the currentDate is lower than minusFive and bigger
    // than plusFive
    [self currentDateIsOutsideTheWindow];
} else {
    [self currentDateIsInsideTheWindow];
}

问题是result1和result2总是给我NSOrderedAscending作为结果,对于任何日期。

任何线索?

感谢。

3 个答案:

答案 0 :(得分:2)

尝试以下代码。

NSTimeInterval ti = [eventDate timeIntervalSinceDate:currentDate];
if (ti > 0 && ti < 300) ...
else if (ti < 0 && ti > -300) ...

答案 1 :(得分:1)

我认为您应该在计算中切换eventDate和currentDate。

答案 2 :(得分:1)

我认为EmptyStack的解决方案对于这个问题是最好的,但我只是将其简化如下:

if( fabs([eventDate timeIntervalSinceNow]) <= 300.0 ) {
  // within the window
} else {
  // outside the window
}

我对此感到好奇......所以我写了一个快速测试,一切都按照我的预期运作。根据下面的示例代码,在第一次运行中,正如预期的那样,正五和{5}是NSOrderedAscending,而负五是NSOrderedDescending。在第二次运行中,与现在三分钟后的日期相比,加五是NSOrderedAscending而五是NSOrderedDescending。最后,加上五个NSOrderedDescending,减去五个也是NSOrderedDescending与二十分钟后的日期相比,再次,一切都符合预期。

// datetest.m
// clang -o datetest datetest.m -framework foundation

#import <Foundation/Foundation.h>

void test_compare(NSDate* event_date)
{
    NSDate* dateNow = [NSDate date];

    NSDate* minusFive = [event_date dateByAddingTimeInterval:-300.0];
    NSDate* plusFive = [event_date dateByAddingTimeInterval:300.0];

    NSComparisonResult minusFiveResult = [dateNow compare:minusFive];
    NSComparisonResult plusFiveResult = [dateNow compare:plusFive];

    NSLog(@"P5: %ld, M5: %ld; dates (now, event, p5, m5):\n\t%@\n\t%@\n\t%@\n\t%@", (long int)plusFiveResult, (long int)minusFiveResult, 
        dateNow, event_date, plusFive, minusFive);  
}

int main (int argc, char const *argv[])
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    // test for an event that's "now"
    NSDate* now = [NSDate date];
    test_compare(now);

    // test for an event that's three minutes from now
    NSDate* threeMinutesLater = [now dateByAddingTimeInterval:180.0];
    test_compare(threeMinutesLater);

    // test for an event that's 20 minutes ago
    NSDate* twentyMinutesBefore = [now dateByAddingTimeInterval:-1200.0];
    test_compare(twentyMinutesBefore);

    [pool drain];
    return 0;
}