我是iOS和编程的新手,我需要以某种方式从当月的第一天到今天获得一个阵列。过去3个月到今天一个阵列,但我不知道该怎么做,请任何帮助或想法?
我检查了这个以获得每月的第一天:
extension Date {
func startOfMonth() -> Date? {
let comp: DateComponents = Calendar.current.dateComponents([.year, .month, .hour], from: Calendar.current.startOfDay(for: self))
return Calendar.current.date(from: comp)!
}
但它仅适用于ViewController,如果在我的项目的其他部分执行此操作该怎么办?而且我也不知道如何迭代数组以获得第一天和今天之间的所有日子......
修改
我做了这样的事情,但它给了一个无限的循环..我做错了什么?
func weatherDatesFromCurrentDayMonth() -> [Any] {
var date = Date()
let currentCalendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.month = -1
// dateComponents.day = 1
let endingDate = Calendar.current.date(byAdding: dateComponents, to: date)
print("\(endingDate!)")
var datesArray = Array<Any>()
while date.compare(endingDate!) != ComparisonResult.orderedAscending
{
var dateComponents = DateComponents()
dateComponents.day = 1
date = Calendar.current.date(byAdding: dateComponents, to: date)!
datesArray.append(date)
print("\(datesArray)")
}
return [datesArray]
}
答案 0 :(得分:2)
你有无限循环,因为一开始你的endingDate
已经是一个月了,date
现在已经开始了。由于在循环内部只增加date
,因此它永远不会在endingDate
之后,因此您的条件始终为true
试试这段代码:
func weatherDatesFromCurrentDayMonth() -> [Date] {
let now = Date()
var currentDate = previousMonth(date: now)
var datesArray = [Date]()
while currentDate < now {
datesArray.append(currentDate)
currentDate = nextDay(date:currentDate)
}
print("result: \(datesArray)")
return datesArray
}
func nextDay(date: Date) -> Date {
var dateComponents = DateComponents()
dateComponents.day = 1
return Calendar.current.date(byAdding: dateComponents, to: date)!
}
func previousMonth(date: Date) -> Date {
var dateComponents = DateComponents()
dateComponents.month = -1
return Calendar.current.date(byAdding: dateComponents, to: date)!
}