2

I am new in iOS and programming and I need somehow to get an array from the first day of current month till today. And one array for past 3 months till today, but I have no idea how to do that, please any help or ideas?

I checked about this to get the first day of month:

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

but it works only in a ViewController, what to do if do that in other part of my project? and also I have no idea how to iterate the array to get all the days between first day and today...

EDIT

I made something like this, but it gives ma an infinite loops.. what am I doing wrong?

    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]

}

1 Answer 1

2

You're having an endless loop because at the beginning your endingDate is already one month ago and date is now. Since inside the loop you only increment date it will never always be after endingDate and thus your condition is always true

Try this code:

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)!
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.