gpt4 book ai didi

ios - 两个日期之间的 Swift 分钟间隔

转载 作者:行者123 更新时间:2023-12-02 02:09:49 24 4
gpt4 key购买 nike

我想返回一个日期数组,其中每个日期都是开始日期和结束日期之间的 15 分钟间隔

即:startDate 时间是 2pm,endDate 时间是 3pm,期望的结果将是一个包含以下日期的数组 [2:15pm, 2:30pm , 2:45pm] 日期格式。

我收集了一些框架代码,但还没有达到我想要的结果。

private func getTimeIntervals(startTime: Date, endTime: Date) -> [Date] {
let timeIntervals = []
//get both times sinces refrenced date and divide by 60 to get minutes
let startTimeMinutes = startTime.timeIntervalSinceReferenceDate/60
let endTimeMinutes = endTime.timeIntervalSinceReferenceDate/60

while(startTimeMinutes < endTimeMinutes) {
// Add each 15 minute Date time interval into the timeIntervalsArray
}

return timeIntervals
}

任何帮助将不胜感激,提前致谢。

最佳答案

使用日历函数date(byAdding:value:to:wrappingComponents:)

func dates(fromStart start: Date,
toEnd end: Date,
component: Calendar.Component,
value: Int) -> [Date] {
var result = [Date]()
var working = start
repeat {
result.append(working)
guard let new = Calendar.current.date(byAdding: component, value: value, to: working) else { return result }
working = new
} while working <= end
return result
}

这是运行中的 playground 中的代码:

import UIKit

func dates(fromStart start: Date,
toEnd end: Date,
component: Calendar.Component,
value: Int) -> [Date] {
var result = [Date]()
var working = start
repeat {
result.append(working)
guard let new = Calendar.current.date(byAdding: component, value: value, to: working) else { return result }
working = new
} while working <= end
return result
}

extension Date {
var localDate: String {return DateFormatter.localizedString(from: self, dateStyle: .medium, timeStyle: .medium)}
}

let threePMComponents = DateComponents(year: 2021, month: 6, day: 7, hour: 15)
guard let threePM = Calendar.current.date(from: threePMComponents) else {
fatalError()
}

let sixPMComponents = DateComponents(year: 2021, month: 6, day: 7, hour: 18)
guard let sixPM = Calendar.current.date(from: sixPMComponents) else {
fatalError()
}

print("Start time = \(threePM.localDate)")
print("End time = \(sixPM.localDate)")


let datesInRange = dates(fromStart: threePM, toEnd: sixPM, component: .minute, value: 15)
for item in datesInRange {
print(item.localDate)
}

输出是:

Start time = Jun 7, 2021 at 3:00:00 PM
End time = Jun 7, 2021 at 6:00:00 PM
Jun 7, 2021 at 3:00:00 PM
Jun 7, 2021 at 3:15:00 PM
Jun 7, 2021 at 3:30:00 PM
Jun 7, 2021 at 3:45:00 PM
Jun 7, 2021 at 4:00:00 PM
Jun 7, 2021 at 4:15:00 PM
Jun 7, 2021 at 4:30:00 PM
Jun 7, 2021 at 4:45:00 PM
Jun 7, 2021 at 5:00:00 PM
Jun 7, 2021 at 5:15:00 PM
Jun 7, 2021 at 5:30:00 PM
Jun 7, 2021 at 5:45:00 PM
Jun 7, 2021 at 6:00:00 PM

如果您希望函数“捕捉”到指定日历组件的下一个偶数间隔,它会更加复杂。

关于ios - 两个日期之间的 Swift 分钟间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67875662/

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