创建时间间隔列表 Swift 3

Create a list of Time Interval Swift 3

我想像这样创建一个时间元组列表;每小时从 0 到 23。

tuple = [(2017-03-24 00:00:00 +0000, 0.0), (2017-03-24 00:01:00 +0000, 0.0), (2017-03-24 00:02:00 +0000, 0.0), (2017-03-24 00:03:00 +0000, 0.0)]

我曾尝试使用此代码获取小时和分钟,但我似乎无法弄清楚如何添加当前月份、日期和年份。或者调整Struct中的日期格式。

感谢您的帮助。这是我正在使用的结构...

import Foundation

struct TimeDay {

let start: TimeInterval
let end: TimeInterval
let interval: TimeInterval

init(start: TimeInterval, interval: TimeInterval, end: TimeInterval) {
    self.start = start
    self.interval = interval
    self.end = end
}

init(startHour: TimeInterval, intervalMinutes: TimeInterval, endHour: TimeInterval) {
    self.start = startHour * 60 * 60
    self.end = endHour * 60 * 60
    self.interval = intervalMinutes * 60
}

var timeRepresentations: [String] {
    let dateComponentFormatter = DateComponentsFormatter()
    dateComponentFormatter.unitsStyle = .positional
    dateComponentFormatter.allowedUnits = [.minute, .hour]

    let dateComponent = NSDateComponents()
    return timeIntervals.map { timeInterval in
        dateComponent.second = Int(timeInterval)
        return dateComponentFormatter.string(from: dateComponent as DateComponents)!
    }
}

var timeIntervals: [TimeInterval]{
    return Array(stride(from: start, through: end, by: interval))
}
}

你的意思是这样的?

struct TimeDay {
    let start: TimeInterval
    let end: TimeInterval
    let interval:TimeInterval
    let fmt = DateFormatter()

    init(start: TimeInterval, interval: TimeInterval, end: TimeInterval) {
        self.start = start
        self.interval = interval
        self.end = end
    }

    init(startHour: TimeInterval, intervalMinutes: TimeInterval, endHour: TimeInterval) {
        self.start = startHour * 60 * 60
        self.end = endHour * 60 * 60
        self.interval = intervalMinutes * 60
    }

    var timeRepresentations: [String] {
        fmt.dateFormat = "yyyy-MM-dd HH:mm:ss z"
        var dateComponent = DateComponents()
        guard let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian) else {
            return []
        }
        dateComponent = calendar.components(in: TimeZone.current, from:Date())
        dateComponent.hour = 0
        dateComponent.minute = 0
        return timeIntervals.map { timeInterval in
            dateComponent.second = Int(timeInterval)
            let dt = calendar.date(from:dateComponent)
            return fmt.string(from:dt!)
        }
    }

    var timeIntervals: [TimeInterval]{
        return Array(stride(from: start, through: end, by: interval))
    }
}

您可能需要为 DateFormatter 调整 dateFormat 以获得您想要的确切输出,但这应该主要按照您想要的方式工作。

一个月可以有 28 到 31 天。您无法将其转换为精确的秒数。使用 DateComponents 存储您的步数:

struct TimeDay {
    var startDate: Date
    var endDate: Date
    var step: DateComponents

    var calendar = Calendar.autoupdatingCurrent
    var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return formatter
    }()

    init(startDate: Date, endDate: Date, step: DateComponents) {
        self.startDate = startDate
        self.endDate   = endDate
        self.step      = step
    }

    var timeIntervals : [Date] {
        guard self.startDate <= self.endDate else {
            return []
        }

        var result = [self.startDate]
        var date = self.startDate
        while date < self.endDate {
            date = self.calendar.date(byAdding: step, to: date)!
            result.append(date)
        }

        return result
    }

    var timeRepresentation : [String] {
        return self.timeIntervals.map { self.dateFormatter.string(from: [=10=]) }
    }
}

示例 1:按小时迭代

let startDate1 = DateComponents(calendar: .current, year: 2017, month: 3, day: 24).date!
let endDate1   = DateComponents(calendar: .current, year: 2017, month: 3, day: 25).date!

let t1 = TimeDay(startDate: startDate1, endDate: endDate1, step: DateComponents(hour: 1))
print(t1.timeRepresentation)

示例 2: 按月迭代

// Iterate by month
let startDate2 = DateComponents(calendar: .current, year: 2017, month: 1, day: 1).date!
let endDate2   = DateComponents(calendar: .current, year: 2017, month: 12, day: 31).date!

let t2 = TimeDay(startDate: startDate2, endDate: endDate2, step: DateComponents(month: 1))
print(t2.timeRepresentation)

示例3:您也可以混合时间单位并按1个月5天进行迭代:

let t3 = TimeDay(startDate: startDate2, endDate: endDate2, step: DateComponents(month: 1, day: 5))
print(t3.timeRepresentation)

编辑:

如果要查找最近的小时:(1) 前进到下一个小时; (2) 倒退到最后一个小时; (3) select 最接近指定日期的那个

let date = Date()    
let closestHour = ([.backward, .forward] as [Calendar.SearchDirection])
    .flatMap { Calendar.current.nextDate(after: date, matching: DateComponents(minute: 0), matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: [=14=]) }
    .min { abs([=14=].timeIntervalSince(date)) <  abs(.timeIntervalSince(date)) }