在nsmutablearray中单独的未来日期

时间:2015-02-09 09:05:17

标签: ios objective-c nsmutablearray nsarray nsdate

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

这是我的阵列:

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;}}

3 个答案:

答案 0 :(得分:1)

你可以使用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,则会为您提供将来的日期。

答案 1 :(得分:0)

您的数组是字符串格式而不是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];

然后你可以办理检查。

答案 2 :(得分:0)

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]];
}
}

这是一个想法。对不起,我没有经过测试就在记事本中编码。