ios8 - 查看记录是过去还是未来

时间:2015-02-11 20:21:00

标签: ios nsdate nsdatecomponent

我正在解析一个数组,想要在之前删除记录

我有这段代码:

int i = 0;
    for (i=0; i < tempArray.count; i++) {
        currentObjectArray = tempArray[i];
        NSString *dateString = [currentObjectArray valueForKey:@"ScheduleTime" ];
        NSDate *schedule = [dateFormatter dateFromString:dateString];
        NSLog(@"schedule: %lu", (unsigned long) schedule );
        NSLog(@"now: %lu", (unsigned long)[NSDate date] );

        NSTimeInterval distanceBetweenDates = [schedule timeIntervalSinceDate: schedule];

NSLog(@"distanceBetweenDates: %lu", (unsigned long)distanceBetweenDates );

结果:

 schedule: 16436914033316069376
 now: 6174145184
 distanceBetweenDates: 0

但是两个结果数字不正确,因此结果不正确。有人可以告诉我我做错了什么吗?感谢

更新:感谢下面的回答,我更新了我的代码如下:

NSString *dateString = [currentObjectArray valueForKey:@"ScheduleTime" ];
        NSDate *schedule = [dateFormatter dateFromString:dateString];

        float s = [schedule timeIntervalSince1970];
        NSLog(@" %f", s );

        NSTimeInterval timeInterval = [currentObjectArray timeIntervalSinceNow];
        if (timeInterval > 0) {
            NSLog(@"YES");
        } else {
            NSLog(@"NO");

The schedule date format is: "YYYY-MM-DD'T'HH:mm:ss"

Update2:我忘了在当地时区添加。感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这两条线不能做你认为他们做的事。

NSLog(@"schedule: %lu", (unsigned long) schedule );
NSLog(@"now: %lu", (unsigned long)[NSDate date] );

执行此类型转换是要求系统向对象返回指针unsigned long表示形式,该对象是一个内存地址,与时间无关。您可能实际上想要询问NSTimeInterval值。

NSLog(@"schedule: %f", [schedule timeIntervalSince1970] );
NSLog(@"now: %f", [[NSDate date] timeIntervalSince1970] );

使你的困惑更加复杂,你也误解了这句话:

NSTimeInterval distanceBetweenDates = [schedule timeIntervalSinceDate: schedule];

您要求系统告诉您scheduleschedule之间的秒数;这显然总是0因为它们是相同的。相反,你可能意味着以下之一:

NSTimeInterval distanceBetweenDates1 = [[NSDate date] timeIntervalSinceDate:schedule];
NSTimeInterval distanceBetweenDates2 = [schedule timeIntervalSinceDate:[NSDate date]];

答案 1 :(得分:1)

您只需要检查时间间隔是负数还是正数,以确定时间分别是之前还是之后。

- (BOOL)isDateInPast:(NSDate *)date {
    NSTimeInterval timeInterval = [date timeIntervalSinceNow];
    if (timeInterval < 0) {
        return YES;
    } else {
        return NO;
    }
}

请注意,这不会检查时间间隔为0(现在)的条件。

编辑:添加此内容以进一步说明。你的循环代码看起来像这样......

NSMutableArray *datesOnlyInFuture = [NSMutableArray array];
for (NSDate *date in dateArray) {
    if (![self isDateInPast:date]) {
        [datesOnlyInFuture addObject:date];
    }
}
NSLog(@"Future only dates: %@", datesOnlyInFuture);

这实际上会为您创建一个新数组。显然应该进行大量的优化。例如,timeIntervalSinceNow每次调用时都会有所不同,因此您可以传入循环开始之前设置的常量日期,这样您就可以始终检查相同的日期/时间。