两次在Objective-C中的比较

我有像下面的时间arrays

"00:00", "01:25", "02:00", "02:35", "04:35", "05:00", "06:00", "07:00", "09:00", "16:30", "17:30", "18:00", "18:30", "19:30", "21:30", "22:00", "22:30", "23:00" 

如何获得当前时间附近的对象索引?

你可以得到这样的时差

 NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [gregorian components:(NSDayCalendarUnit | NSHourCalendarUnit | NSMinCalendarUnit) fromDate:today]; [components setHour:otherHour]; [components setMinute:otherMinute]; NSDate *otherDate = [gregorian dateFromComponents:components]; NSTimeInterval timeDifferenceBetweenDates = [today timeIntervalSinceDate:otherDate]; 

在所有的小时/分钟内完成这个工作,并采取最小的绝对时间间隔。

我在date和时间编程方面没有太多的经验,但是我认为你可以在date和时间编程指南的日历计算部分find相关的东西。 也检查出NSDateComponents的文档。

如果你正在尝试使用string数组来使用NSDateFormatter将这个string转换为NSDate对象。 之后,您可以将值与当前date进行比较。 你可以做这样的事情:

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"HH:mm"]; NSDate *formattedCurrentDate = [dateFormat dateFromString:[dateFormat stringFromDate:[NSDate date]]]; for(NSString *stringTime in times) { NSDate *dateFromString = [dateFormat dateFromString:stringTime]; if([formattedCurrentDate earlierDate:dateFromString]) { // current time is earlier that time (...) } } 

您可能需要使用timeIntervalSinceDate方法。 循环访问您的数组,并logging最小TimeInterval。 以最小值存储date

 NSTimeInterval *minimumInterval; NSDate *closestDate; forin(NSDate *someTime in timeArray) { NSTimeInterval timeInt = [[NSDate date] timeIntervalSinceDate:someTime]; //someTime = any date from your array //compare timeInterval here if(minumumInterval > timeInt || minimumInterval == nil) { minimumInterval = timeInt; closestDate = someTime; } } 

在这个循环结束时,您将拥有从arrays到当前时间的最近date。

这将为你做的伎俩。

我不是最好的C ++,但我可以给你一点我将遵循的方向:

这可以像字节到kb / mb / gbparsing器中的一些字节那样完成,我会这么做的方法是将时间改为“军事”时间,这样可以将值存储为整数,如下所示:

 0000, 0125, 0200, 0235, ... 

这当然有0000明显低于 2300的缺陷,但是这里有:

如果您然后查看数组并比较值:

让我们假设我们有时间12:00,那当然应该翻译成1200,所以:

 int array_length = arr.length; // we store this for later use int cur_time = 1200; for (int i=0; i<array_length; i++) { if (cur_time > arr[i] and < arr[i+1]) { // this should be close enough. first time around. int array_index = i; } } 

然后你知道“假定的”最接近的值的索引值,并将其与索引的较低和较高部分进行比较,当然,检查它是否是数组中的第一个或最后一个值:

 int assumed_value = arr[array_index]; int higher_value = 0; if (array_index == array_length) { // take the first value as the "highest" higher_value = arr[0]; } else { // otherwise just do your thing: higher_value = arr[array_index + 1]; } 

我们应该有(在我们的例子中):

 assumed_value = 0900; higher_value = 1630; // and just for reference: cur_time = 1200; 

现在我们发现最接近我们想要的价值:

 int highest_value = higher_value - cur_time; // 430; int lowest_value = cur_time - lower_value; // 300; if (highest_value > lowest_value) { // we have a winner, the assumed value was closest! } else { // otherwise the highest_value is the closest one, but not in our use case } 

哦,顺便说一句。 我想我只是在那里做了我自己的语言。