gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:37:37 25 4
gpt4 key购买 nike

我正在尝试获取最后一小时的每 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*$0, to: previousHourTenth)! } }
}

Playground 测试

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 来根据需要向用户显示这些日期。

关于ios - 在 10 分钟切片中拆分最后两个小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58098867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com