我如何创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;
- 苹果基于Swift的iBeacon应用开发,带有适用于iOS 7/8的CoreLocation
- 不调用GetHeightForHeader和GetViewForHeader
- 在Watch App中创buildWKInterfaceImage的进度圈
- 我怎样才能从AppDelegate TabBarController的ViewController?
- 如何删除所有UserDefaults数据? – 斯威夫特
- 如何将这个数组分割成单独的元素/数组,以便在Swift的Table中使用?
- FIrebase iOS集成崩溃 – 由无效的GOOGLE_APP_ID引起
- Jazzy不能按照预期生成快速文档
- Swift中的树数据结构