我是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]

}

最佳答案

您之所以无休止地循环,是因为开始时您的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)!
}

关于ios - 从每月的第一天到今天,获取一系列天数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40364663/

10-10 01:04