2014-05-06 9 views
-5

我想要创建一个时间数组,并通过它们排序来查找数组中下一个最接近的时间(如果它经过一段时间,那么它将选择下一个最接近的时间)。我怎样才能做到这一点?我不希望它指定年,月或日。我只想过滤一天中的时间(小时,分钟,秒)。我想在NSArray的下一次获得多少秒。我已经看过NSDate,并注意到有一个timeIntervalSinceDate方法,但我不知道如何创建NSDate对象来进行比较。如何创建特定时间的数组?

回答

0
NSDate * date = [NSDate date]; 
NSArray * array = @[]; 
NSUInteger index = 
[array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { 
    return ![[((NSDate *)obj) earlierDate:date] isEqualToDate:date]; 
}]; 
NSDate * refDate = nil; 

if (index != NSNotFound) 
    refDate = array[index]; 
0

另一张海报给了你一个使用NSDates的解决方案。 NSDates是指定时间(包括年,月,日,小时,分钟,秒和秒的小数部分)的对象。

如果要使用仅反映小时/分钟/秒的时间,我建议你只使用基于秒/天的整数运算:

NSUInteger totalSeconds = hours * 60 * 60 + minutes * 60 seconds; 

然后,您可以创建持有分秒必争一个NSNumber的NSArray的值,并根据需要操纵它们。

你可以写信给时/分/秒值转换为一个NSNumber的方法:

- (NSNumber *) numberWithHour: (NSUInteger) hour 
    minute: (NSUInteger) minute 
    second: (NSUInteger) second; 
{ 
    return @(hour*60*60 + minute*60 second); 
} 

,然后使用该方法来创建NSNumbers

数组
NSMutableArray *timesArray = [NSMutableArray new]; 
[timesArray addObject: [self numberWithHour: 7 minute: 30 second: 0]]; 
[timesArray addObject: [self numberWithHour: 9 minute: 23 second: 17]]; 
[timesArray addObject: [self numberWithHour: 12 minute: 3 second: 52]]; 
[timesArray addObject: [self numberWithHour: 23 minute: 53 second: 59]]; 
}; 

要获取小时/分钟/秒,您可以使用NSDate,NSCalendar和NSDateComponents:

NSDate *now = [NSDate date]; 
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar]; 

NSDateComponents comps = 
    [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit 
    fromDate: now]; 
    int hour = [components hour]; 
    int minute = [components minute]; 
    int second = [components second]; 


unsigned long nowTotalSeconds = hours * 60 * 60 + minutes * 60 seconds; 

一旦您计算了今天的总秒数,您可以遍历您的时间值数组,并使用NSArray方法找到未来的未来时间indexOfObjectPassingTest

NSUInteger futureTimeIndex = [timesArray indexOfObjectPassingTest: 
    ^BOOL(NSNumber *obj, NSUInteger idx, BOOL *stop) 
{ 
    if (obj.unsignedIntegerValue > nowTotalSeconds) 
    return idx; 
} 
if (futureTimeIndex != NSNotFound) 
    NSInteger secondsUntilNextTime = 
    timesArray[futureTimeIndex].unsignedIntegerValue - nowTotalSeconds; 
相关问题