Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group array of dates by months in swift?

Tags:

ios

swift

I am working on a scheduling app. I want all the dates of the given months I am not able to group dates by months that is what I tried but I want a different expected result

extension Date {
    static func dates(from fromDate: Date, to toDate: Date) -> [Date] {
        var dates: [Date] = []
        var date = fromDate

        while date <= toDate {
            dates.append(date)
            guard let newDate = Calendar.current.date(byAdding: .day, value: 1, to: date) else { break }
            date = newDate
        }
        return dates
    }
    var month: Int {
        return Calendar.current.component(.month, from: self)
    }
}

let fromDate = Calendar.current.date(byAdding: .day, value: 30, to: Date())
let datesBetweenArray = Date.dates(from: Date(), to: fromDate!)
var sortedDatesByMonth: [[Date]] = []
let filterDatesByMonth = { month in datesBetweenArray.filter { $0.month == month } }
(1...12).forEach { sortedDatesByMonth.append(filterDatesByMonth($0)) }

The result is in this format [[], [], [], [], [], [], [2019-07-31 03:51:19 +0000],……., [], [], [], []]

This kinda result I want expecting

struct ScheduleDates {
    var month: String
    var dates: [Date]

    init(month: String, dates: [Date]) {
        self.month = month
        self.dates = dates
    }
}
var sections = [ScheduleDates]()
like image 536
Gitz Avatar asked Mar 03 '23 15:03

Gitz


1 Answers

If you want to group your dates by month you can create a Dictionary like this:

Dictionary(grouping: datesBetweenArray, by: { $0.month })

This results in the following output of the format [Int: [Date]]

The key of the dictionary will be your month.

Now you can initialize your scheduleDates struct by looping through this dictionary in this way:

var sections = Dictionary(grouping: datesBetweenArray,
                          by: ({$0.month}))
    .map { tuple in
        ScheduleDates(month: String(tuple.0), dates: tuple.1)
}
like image 68
May Rest in Peace Avatar answered Mar 06 '23 22:03

May Rest in Peace