在 NSDate 数组中查找匹配项 - Swift

Find matches in NSDate array - Swift

我在 Swift(和一般编码)和堆栈溢出方面都是新手。 SO 对学习如何编码非常有帮助,因此,非常感谢 SO 社区提供的重要问题和答案。

这是我的第一个 SO 问题……

我已经为这个挑战绞尽脑汁好几天了。我已经阅读并尝试了多种建议的解决方案,但到目前为止,其中 none 对我有用。

我有一个动态 NSDate 数组,它是从网络 API 中检索到的(使用较早的代码)。

[2016-05-01 03:27:22 +0000, 2016-05-01 03:27:24 +0000, 2016-05-01 03:27:25 +0000, 2016-05-01 03:27:27 +0000, 2016-05-03 12:48:07 +0000, 2016-05-03 12:48:09 +0000, 2016-05-03 12:48:11 +0000, 2016-05-03 12:48:13 +0000, 2016-05-03 19:52:46 +0000, 2016-05-03 19:52:51 +0000, 2016-05-03 19:52:56 +0000, 2016-05-04 00:37:27 +0000, 2016-05-04 00:37:30 +0000, 2016-05-04 12:36:17 +0000, 2016-05-04 12:36:19 +0000, 2016-05-04 12:46:26 +0000, 2016-05-04 12:46:28 +0000, 2016-05-04 17:39:31 +0000, 2016-05-04 17:39:34 +0000, 2016-05-04 17:54:24 +0000, 2016-05-04 23:46:20 +0000]

我设置了一个循环遍历上述数组的方法,并检查数组中是否有任何项目在最后 x 分钟内带有时间戳。

    func prepareJSONData1 () {

    let currentDate = NSDate()
    var startDate = currentDate.dateByAddingTimeInterval(-5 * 60) //sets the start date to 5 minutes prior to current time


    while startDate.compare(currentDate) != NSComparisonResult.OrderedDescending  {

        var i = Int(0) //setting up a counter

        for i in 0...self.quantumArrayNSDate.count - 1 {

            if startDate == self.quantumArrayNSDate[i] {
                print("Data entry found for \(startDate) timestamp")
            }
            self.i += 1
        }

        startDate = startDate.dateByAddingTimeInterval(1) //increment through the NSDate range

    }
}

无论我设置开始日期有多早(即使我倒退几个月),我都无法将此代码用于 return 匹配项。我怀疑我没有正确设置 startDate 变量,因为如果我将那段代码更改为:

startDate = quantumArrayNSDate.first!

然后代码 returns 数组中的所有项目,正如我所期望的那样。

我也尝试过这种其他方法但没有成功:

let calendar = NSCalendar.currentCalendar()
    let startDate = calendar.dateByAddingUnit(.Minute, value: -5, toDate: NSDate(), options: [])!     // <- this didn't work

如果有人能指出我做错了什么并提出解决方案,我将不胜感激。谢谢!

NSDate表示一个时间点,存储为时间间隔 自参考日期 2001 年 1 月 1 日以来的秒数,UTC。这个时间间隔是一个浮点数(NSTimeInterval aka Double) 并且还包括小数秒。所以两个 NSDates 在同一秒内创建的可以不同:

let date1 = NSDate()
let date2 = NSDate()
print(date1 == date2)
// false
print(date2.timeIntervalSinceDate(date1))
// 5.00679016113281e-06

你的平等测试

if startDate == self.quantumArrayNSDate[i]

失败,除非两个日期表示完全相同的时间点 小数秒精度。

您可以在给定时间间隔内迭代日期

for date in quantumArrayNSDate {
    if date.compare(startDate) == .OrderedDescending
     && date.compare(currentDate) == .OrderedAscending {
        // ... 
    }
}

或获取与

匹配的日期列表
let filteredDates = quantumArrayNSDate.filter { date in
    date.compare(startDate) == .OrderedDescending
        && date.compare(currentDate) == .OrderedAscending
}

要检查两个日期是否等于秒粒度,您可以使用

if calendar.compareDate(date, toDate: currentDate, toUnitGranularity: .Second) == .OrderedSame {
   // ...
}