我如何创build一个特定时间的数组?

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

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

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

如果你想使用只反映小时/分钟/秒的时间,我build议你只使用基于秒/天的整数math:

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

然后,您可以创build一个NSNumber值的NSArray,它保存第二个计数,并根据需要操作它们。

您可能会编写一个方法将小时/分钟/秒的值转换为NSNumber:

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

然后使用该方法创build一个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]]; }; 

要获得当前date的小时/分钟/秒,您可以使用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方法indexOfObjectPassingTestfind下一个未来的时间

 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;