从NSDate数组中查找下一个最接近的日期

时间:2015-09-26 08:39:28

标签: ios objective-c nsdate nsdateformatter

我如何从一系列时间中找到下一个祷告,我在不同的时间总共有6个祷告,我想将每个祷告与当前时间进行比较,并且必须找出哪一个最接近作为下一个祷告,日期格式也会产生问题,因为它始终以UTC格式提供,我必须使用本地时区,我使用以下代码:

NSMutableArray *arrayTimeIntervals = [[NSMutableArray alloc]init];
NSMutableArray *intervals = [[NSMutableArray alloc]init];

NSMutableArray *arrayPrayers = [[NSMutableArray alloc]init];

[arrayPrayers addObject:@{@"prayer":@"prayer 1",@"time":@"1:12 am"}];
[arrayPrayers addObject:@{@"prayer":@"prayer 2",@"time":@"5:45 am"}];
[arrayPrayers addObject:@{@"prayer":@"prayer 3",@"time":@"12:03 pm"}];
[arrayPrayers addObject:@{@"prayer":@"prayer 4",@"time":@"3:30 pm"}];
[arrayPrayers addObject:@{@"prayer":@"prayer 4",@"time":@"6:20 pm"}];
[arrayPrayers addObject:@{@"prayer":@"prayer 6",@"time":@"7:50 pm"}];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];

NSMutableArray *dates = [NSMutableArray arrayWithCapacity:arrayPrayers.count];
for (NSDictionary *timeDict in arrayPrayers)
{
    NSString *timeString = [timeDict objectForKey:@"time"];
    NSString *name = [timeDict objectForKey:@"prayer"];
    NSDate *date = [dateFormatter dateFromString:timeString];
    [dates addObject:@{@"prayer":name,@"time":timeString, @"date":date}];
}


for (int i =0 ; i<arrayPrayers.count; i++) {


    NSDictionary *timeDict = arrayPrayers[i];
    NSString *timeString = [timeDict objectForKey:@"time"];
    //NSString *name = [timeDict objectForKey:@"prayer"];
    NSDate *date = [dateFormatter dateFromString:timeString];

    NSComparisonResult result = [[NSDate date] compare:date];
    if(result==NSOrderedAscending){
        NSLog(@"next prayer");
    }else if(result==NSOrderedDescending){
        NSLog(@"last prayer");
    }else{
        NSLog(@"current prayer");
    }

    if ([date earlierDate:[NSDate date]]) {
        NSTimeInterval interval = [date timeIntervalSinceNow];
        NSDictionary *tempDict = @{@"Prayer":timeDict,
                                   @"Time":timeString,
                                   @"Index":[NSString stringWithFormat:@"%d",i],
                                   @"Interval":[NSString stringWithFormat:@"%f",interval]};
        [arrayTimeIntervals addObject:tempDict];
        [intervals addObject:[NSString stringWithFormat:@"%f",interval]];
    }
}

NSNumber * min = [intervals valueForKeyPath:@"@min.doubleValue"];

NSUInteger index = 0;
for(int i =0 ; i<intervals.count; i++)
{
    NSDictionary* dict = arrayTimeIntervals[i];
    if([[dict objectForKey:@"Interval"] intValue] == [min intValue]) {
        index = i;
        NSLog(@"next prayer is!!!:%ld",index);
        break;
    }
}

NSDictionary *dict = [arrayTimeIntervals objectAtIndex:index];
NSLog(@"next prayer object is:%@",dict);

0 个答案:

没有答案