在 nsmutablearray 中单独的未来日期

separate future date in nsmutablearray

我在该数组中有一个可变数组,我只有过去日期、当前日期和未来日期。我必须将未来的日期和存储分开到另一个数组中。你能帮帮我吗

这是我的数组:

uniqueItems(
    "2015-03-01",
    "2015-02-28",
    "2015-02-22",
    "2015-02-21",
    "2015-02-20",
    "2015-02-15",
    "2015-02-14",
    "2015-02-13",
    "2015-02-08",
    "2015-02-07",
    "2015-02-01",
    "2015-01-31",
    "2015-01-30",
    "2015-01-25",
    "2015-01-24",
    "2015-01-18",
    "2015-01-17",
    "2015-01-16",
    "2015-01-11",
    "2015-01-10",
    "2014-12-07"

我已经尝试过这种编码,但没有用。

NSDate *currentDate = [NSDate date];
 NSDate* dateAdded=(NSDate*)[uniqueItems objectAtIndex:0];
 double min = [currentDate timeIntervalSinceDate:dateAdded];
int minIndex = 0;
 for (int i = 1; i < [uniqueItems count]; ++i)
{

    double currentmin = [currentDate timeIntervalSinceDate:[uniqueItems objectAtIndex:i]];
    if (currentmin < min) {
        min = currentmin;
        minIndex = i;}}

您的数组是字符串格式,不是 NSDate 对象。您可以将字符串转换为 nsdate

NSString *dateString = @"2010-02-13";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];

然后你就可以检查了。

NSDate *currentDate = [NSDate date];
NSDate *date;
int offset = 0;
NSMutableArray *futureArray = [[NSMutableArray alloc] init];
for (int i = 1; i < [uniqueItems count]; ++i)
{
    date = [uniqueItems objectAtIndex:i];//TODO: Convert to NSDate
    offset = [currentDate timeIntervalSinceDate:date];
    if (offset < 0) {
    [futureArray addObject:[uniqueItems objectAtIndex:i]];
}
}

这是一个想法。抱歉,我没有测试就在记事本中编码。

您可以为此使用 NSPredicate 块。您的数组不包含 NSDate 个对象,因此我们需要将其转换为 NSDate 然后与 [NSDate date]

进行比较
NSPredicate *findFutureDates = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind){
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"yyyy-MM-dd"];
    [df setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *dd = [df dateFromString:(NSString *)obj ];
    return ([[NSDate date] compare:dd] == NSOrderedAscending);
}];

NSArray *arrFutureDates = [yourArray filteredArrayUsingPredicate: findFutureDates];
NSLog(@"%@",arrFutureDates);

如果你通过 NSOrderedAscending 会给你未来的日期如果你通过 NSOrderedDescending 会给你过去的日期。