一种返回两个日期之间的日期数组的方法-Swift 3 [英] A method which returns an array of dates that are in between two dates - Swift 3
本文介绍了一种返回两个日期之间的日期数组的方法-Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取一个对象的时间戳与未来30天之间的日期数组。
I'm trying to get an array of dates between the time stamp of one of my objects and 30 days into the future.
我使用了下面的代码,但是我没有得到想要的结果,并且在尝试创建标题中描述的方法时遇到了麻烦。任何帮助都会很棒,谢谢。
I've used the code below but i'm not getting the desired result and am having trouble trying to make a method described in the title. Any help would be great, thank you.
var dates = [Date]()
func fetchDays() {
let cal = Calendar.current
var dateComponents = DateComponents()
dateComponents.year = 2017
dateComponents.month = 2
dateComponents.day = 12
guard let startDate = cal.date(from: dateComponents) else {
return }
var start = cal.startOfDay(for: startDate)
for _ in 0 ... 30 {
guard let daysBetween = cal.date(byAdding: .day, value: 1, to: startDate) else { return }
start = daysBetween
dates.append(start)
}
}
推荐答案
您将1加上相同的开始日期,因此您的数组将一遍又一遍地填充相同的日期。只需将 1
替换为循环索引+ 1。
You are adding 1 to the same start date so your array is filled with the same date over and over. Simply replace 1
with the loop index + 1.
for i in 0 ... 30 {
if let newDate = cal.date(byAdding: .day, value: i + 1, to: startDate) {
dates.append(newDate)
}
}
您不需要开始
变量。
这篇关于一种返回两个日期之间的日期数组的方法-Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文