使用JSON(EPOCH)中的毫秒从数组(和返回索引)中查找最近的时间



目前正在寻找一个解决方案,以使用毫秒查找与当前日期相比最近的日期我理解需要发生的部分逻辑,但对这一切仍有点模糊。

希望显示与当前时间相关的下一个潮汐。获取索引并显示数据

我知道我会找到德尔塔,并将2次和德尔塔最小的一次进行比较,对吗?并对它们进行迭代。

下面是我到目前为止工作的代码,我只需要条件和逻辑计算出

NSNumber *tideDateEPOCH = [eachTideSummary valueForKeyPath:@"date.epoch"];
NSTimeInterval dateDeltaInterval = [tideDateEPOCH doubleValue];
NSTimeInterval dateDelta = dateDeltaInterval -  todayInEPOCH;
NSLog(@"tideDateEPOCH: %@", tideDateEPOCH);
NSLog(@"dateDelta: %f", dateDelta);
// Perform if conditional to see if the tide time array is the closest to the current date
// Return that index, then grab that index, display data within that index to the user (this is the next time information)

下面是正在返回的tideSummary数组的示例。参见date.epoch

"tideSummary": [
{
"date": {
"pretty": "11:58 AM PST on December 19, 2013",
"year": "2013",
"mon": "12",
"mday": "19",
"hour": "11",
"min": "58",
"tzname": "America/Los_Angeles",
"epoch": "1387483136"
},

我心目中的逻辑(需要一些帮助和完善)

  • tideSummary数组的每个索引执行for循环
  • 循环内部找出从currentTimetideSummary.date.epoch的时间差
  • 这就是我感到困惑的地方。我们有上面两次的区别。是否保存所有索引中最小的时间并返回最小索引值
  • 一旦我们从数组中返回最小的delta索引值。然后我们可以获取这个索引,比如:[tideSummaryArray objectAtIndex:nextTideIndex];

返回的数据看起来像是经过排序的。听起来对吗?我发现了其他关于NSDate的帖子,但如果我有时间在EPOCH,那不是更容易/更快吗?想法?

NSInteger now = (NSInteger) ([[NSDate date] timeIntervalSince1970] * 1000);
NSArray* tideSummary = tide[@"tideSummary"];
for (NSDictionary* tideEntry in tideSummary) {
NSDictionary* utcTime = tideEntry[@"utcdate"];
NSString* timeString = utcTime[@"epoch"];
NSInteger time = timeString.integerValue;
NSInteger deltaTime = time - now;  // I'll let you define "closest"
}

(相反,使用NSTimeIntervals也同样容易。)

最新更新