我有以下时间的数组
"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"
如何得到对象的索引哪个时间接近当前时间?
答案 0 :(得分:3)
你可以得到这样的时差
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];
为所有小时/分钟执行此操作并采用最小绝对时间间隔。
答案 1 :(得分:0)
我在ObjC的日期和时间编程方面没有很多经验,但我认为你可以在日期和时间编程指南的Calendrical Calculations部分找到相关内容。另请查看NSDateComponents的文档。
答案 2 :(得分:0)
如果您尝试使用strings数组执行此操作,请使用NSDateFormatter将此字符串转换为NSDate对象。之后,您可以将值与当前日期进行比较。你可以这样做:
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
(...)
}
}
答案 3 :(得分:0)
您可能想要使用timeIntervalSinceDate方法。循环遍历数组并跟踪最小TimeInterval。以最小值
存储日期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;
}
}
在此循环结束时,您将获得从阵列到当前时间的最接近日期。
这将为你解决问题。
答案 4 :(得分:0)
我不是C ++的佼佼者,但我可以给你一点指示:
这可以像某些字节到kb / mb / gb 解析器那样完成,我会这样做,将时间改为“军事”时间,就像你那样可以将值存储为整数,如下所示:
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
}
哦,顺便说一句。我想我只是在那里编写自己的语言。