ios - 如何过滤时间戳数组以保持特定时间?

标签 ios swift date

想象一下这个时间戳数组[Double]:

hourlyTimes": [1551344400, 1551348000, 1551351600, 1551355200, 1551358800, 1551362400, 1551366000, 1551369600, 1551373200 ... ]

它对应于我要显示数据的时间。

为简单起见,这里是我仅显示小时 (UTC) 时的完整数组:

Hours = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 3, 6, 9, 12, 15, 18, 21, 0, 3, 6, 9, 12, 15, 18, 0, 6, 12, 18, 0, 6, 12, 18, 0, 6, 12, 18, 0, 6, 12, 18, 0, 6, 12, 18, 0]

现在这就是我想要实现的,我需要过滤这个时间戳数组,以便只保留任何一天(每三小时)的这些特定时间。

[0, 3, 6, 9, 12, 15, 18, 21]

好的,现在让我们看一下代码:

let arrayOfTimestamp = time.hourlyTimes
let arrayOfHours = arrayOfTimestamp.map({ Date.init(timeIntervalSince1970: $0).hoursUTC})
let hoursToKeep = [0, 3, 6, 9, 12, 15, 18, 21]
let filtered = arrayOfHours.intersection(with: hoursToKeep)

这里有一些解释:

第一行的

time 是后端的响应,向我返回所有可用的时间戳。

struct MultiForecastTimeModel: Codable {
    let hourlyTimes: [Double]
    let dailyTimes: [Double]
}

.hoursUTC 只是一个 Date 扩展,用于检索 Date 对象的小时部分。

var hoursUTC: Int {
    var calendar = Calendar.current
    let timezone = TimeZone(abbreviation: "UTC")!
    calendar.timeZone = timezone
    return calendar.component(.hour,  from: self)
}

最后,.intersection 也是一个扩展,目的是实现与经典 intersection 相同的功能,同时保留索引和出现次数。

extension Collection where Element: Equatable {

    func intersection(with filter: [Element]) -> [Element] {
        return self.filter { element in filter.contains(element) }
    }
}

一切正常,我唯一的问题是我现在必须将所有这些值关联为一个元组数组。

像这样:

let tuples = Array(zip(filtered, filtered.dropFirst()))

但是有一个实际的时间戳(对应于实际日期),而不仅仅是一个 Int 数组(小时分量)。

因为最后,我要做的是:

self.hourlyMapDataSource.data.value = tuples

我的数据源需要一个时间戳元组 (Double, Double)

class HourlyMapDataSource : GenericDataSource<(Double, Double)>, UICollectionViewDataSource { }

关于我应该如何改进我的代码和/或我的逻辑,您有什么建议吗?

提前谢谢你。

编辑:我的元组数组应该只包含时间已通过 hoursToKeep 数组“验证”的时间戳,因此它在小时之间有 3 小时的差异。

为了简单起见,我将向您展示时间,但这是我想要的实际对应时间戳:

[(9, 12), (12, 15), (15, 18) ...]

最佳答案

var tupleArray = hourlyTimes.map { (time: $0, hour: Date.init(timeIntervalSince1970: $0).hoursUTC)}

现在你可以运行reduce函数了

var selectedHours = tupleArray.filter { return hoursToKeep.contains($0.hour) }

这将为您提供一组具有经过验证的时间的元组,

[(1551344400, 9), (1551348000, 12)]

关于ios - 如何过滤时间戳数组以保持特定时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54923454/

相关文章:

iphone - 使用自定义节标题将行添加到 tableView

java - Jackson 解析日期在某些机器上失败

MySQL date_add,日期子查询

ios - Parse.com-从Parse.com向iOS应用发送消息,不像推送通知

ios - PKPass 错误 "The pass cannot be read because it isn’ t 有效。”

ios - 将 Google map 相机移动到某个位置

javascript - 使用一致的时区解释解析 javascript 日期?

ios - 在 Swift 中使用 NSMutableAttributedString 更改特定文本的颜色

ios - UITableview 返回 nil

ios - 当排列的 subview 的高度均为零时,UIStackView 高度不为 0