在 10 分钟切片中拆分最后两个小时

Split last two hours in 10 minutes slices

我正在尝试获取最后一小时的每 10 分钟。

比如现在是15:46:41

我想要 [15:40:00, 15:30:00, 15:20:00, 15:10:00, 15:00:00, 14:50:00, 14:40:00, 14:30:00、14:20:00、14:10:00、14:00:00、13:50:00、13:40:00]

let calendar = Calendar.current
let now = Date()
var components = DateComponents()
components.hour = -2
if let early = calendar.date(byAdding: components, to: now) {
    let nowMin = calendar.component(.minute, from: early)
    let diff = 10 - (nowMin % 10)
    components.minute = diff
    var minutes: [Int] = []
    for _ in 0...13 {
        // I cant figure out what should I do next.
    }
    print(minutes)
}

您可以获取现在的分钟数,将该值除以 10 的余数,然后从该值中减去它。这样你就得到了最后的第十小时分钟,然后你只需要用与现在相同的小时组件来设置它来找出你的数组的第一个元素。接下来,您可以填充其余日期,从开始日期减去 10 分钟乘以元素位置。像这样尝试:

Xcode 11 • Swift 5.1(对于旧版本只需像往常一样添加 return 语句)

extension Date {
    var hour: Int { Calendar.current.component(.hour, from: self) }
    var minute: Int { Calendar.current.component(.minute, from: self) }
    var previousHourTenth: Date { Calendar.current.date(bySettingHour: hour, minute: minute - minute % 10, second: 0, of: self)! }
    func lastNthHourTenth(n: Int) -> [Date] { (0..<n).map {  Calendar.current.date(byAdding: .minute, value: -10*[=10=], to: previousHourTenth)! } }
}

游乐场测试

Date()                          // "Sep 25, 2019 at 10:19 AM"
Date().previousHourTenth        // "Sep 25, 2019 at 10:10 AM"
Date().lastNthHourTenth(n: 13)  // "Sep 25, 2019 at 10:10 AM", "Sep 25, 2019 at 10:00 AM", "Sep 25, 2019 at 9:50 AM", "Sep 25, 2019 at 9:40 AM", "Sep 25, 2019 at 9:30 AM", "Sep 25, 2019 at 9:20 AM", "Sep 25, 2019 at 9:10 AM", "Sep 25, 2019 at 9:00 AM", "Sep 25, 2019 at 8:50 AM", "Sep 25, 2019 at 8:40 AM", "Sep 25, 2019 at 8:30 AM", "Sep 25, 2019 at 8:20 AM", "Sep 25, 2019 at 8:10 AM"]

现在您只需要使用 DateFormatter 来根据需要向用户显示这些日期。