【问题标题】:Remove times in past from array of times从时间数组中删除过去的时间
【发布时间】:2013-07-04 21:47:21
【问题描述】:

我有很多这样的时间:

(
    "2000-01-01 23:48:00 +0000",
    "2000-01-01 02:15:00 +0000",
    "2000-01-01 04:39:00 +0000",
    "2000-01-01 17:23:00 +0000",
    "2000-01-01 13:02:00 +0000",
    "2000-01-01 21:25:00 +0000"
)

由此代码生成:

//loop through array and convert the string times to NSDates
                NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
                [timeFormatter setDateFormat:@"hh:mm a"];
                NSMutableArray *arrayOfDatesAsDates = [NSMutableArray array];
                for (NSObject* o in arrayTimes)
                {
                    NSLog(@"%@",o);
                    NSDate *nsDateTime = [timeFormatter dateFromString:o];
                    [arrayOfDatesAsDates addObject:nsDateTime];
                }
                NSLog(@"times array: %@", arrayOfDatesAsDates);//

我这样做是因为我试图获取下一个数组中的时间。我的计划是删除过去的时间,订购它们,然后将第一个作为下一次。

如何删除过去的?

谢谢

【问题讨论】:

  • 鉴于日期都是 2000 年,最简单的方法是清空数组...
  • 谁知道!?除了您之外,没有其他人知道 arrayTimes 究竟包含什么。
  • @MarcB 嗯,这只是样本数据,它每次都会改变......

标签: objective-c nsarray nsdate


【解决方案1】:

这样的事情会做......

NSArray *dateArray = ...

NSArray *filteredArray = [dateArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDate *date, NSDictionary *bind){
    NSComparisonResult result = [[NSDate date] compare:date];
    return result == NSOrderedAscending; 
}]];

filteredArray 将是 dateArray 中现在或将来的所有日期。

【讨论】:

    【解决方案2】:

    如果您在问题中的表述是正确的,那么您的时间实际上是具有类似 ISO 日期格式的字符串。

    理论上这很糟糕 - 时间戳应该保留为 NSDates,因为您也在暗示自己。

    但是(如果您确定没有人在看的话)您可以利用 ISO 日期格式允许按字典顺序排序这一事实。字符串“2000-01-01 21:48:00 +0000”排在“2000-01-01 23:48:00 +0000”之前,因此您只需使用表示“now”的字符串进行过滤。

    NSArray *times = @[
        // ... more times
        @"2000-01-01 13:02:00 +0000",
        @"2014-01-01 13:02:00 +0000",
        @"2015-01-01 13:02:00 +0000"
    ];
    
    NSString *nowString = [[NSDate date] descriptionWithLocale: nil];
    
    NSPredicate *stringPred = [NSPredicate predicateWithFormat: @"SELF >= %@", nowString];
    
    NSArray *filteredTimes = [times filteredArrayUsingPredicate: stringPred];
    

    有点hacky,所以记得好好评论它。您可能还想进行一些防御性测试,以确保您的时间戳格式在将来也保持不变。请注意,如果它滑到“2015-2-3 13:02:00 +0000”之类的内容(在月份和日期字段中没有前导零),它将中断,如“2015-10-15 13:02:00 +0000" 将在此之前排序。

    实际上,您可能应该在读取数据后立即将时间戳转换为 NSDate 对象,在这种情况下,谓词保持不变,您只需直接传递 [NSDate date] 而不是其字符串表示形式。

    【讨论】:

      【解决方案3】:

      只需将这些转换为 NSDate 对象并使用比较对数组进行排序:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-08
        • 2012-11-23
        相关资源
        最近更新 更多