将最后两个小时分成 10 分钟的切片



我试图在最后一个小时每 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 分钟乘以。尝试如下:

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)! } }
}

游乐场测试

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"]

现在,您只需要使用日期格式化程序根据需要向用户显示这些日期。

最新更新