Swift:将日期数组分组为几个月

时间:2018-03-21 12:02:21

标签: swift

给定:日期数组:[date1,date2,date3,...,dateN]

通缉:包含日期的月份数组:[[date1,date2],[date3],...] 一个月的所有日子都应该在同一个月的数组内。

有没有办法实现这个功能?我认为必要的方法会很复杂。

1 个答案:

答案 0 :(得分:4)

Swift 4

我就是这样做的,我希望它有所帮助:

extension Date {

    var month: Int {
        return Calendar.current.component(.month, from: self)
    }

}

// some random arbitrary dates
let rawDates = [Date(), Date().addingTimeInterval(100000.0), Date().addingTimeInterval(100000000.0)]
// the desired format
var sortedDatesByMonth: [[Date]] = []

// a filter to filter months by a given integer, you could also pull rawDates out of the equation here, to make it pure functional
let filterDatesByMonth = { month in rawDates.filter { $0.month == month } }
// loop through the months in a calendar and for every month filter the dates and append them to the array
(1...12).forEach { sortedDatesByMonth.append(filterDatesByMonth($0)) }

Xcode 9.2 游乐场中测试并工作。

输出

[[], [], [2018-03-21 12:29:10 +0000, 2018-03-22 16:15:50 +0000], [], [2021-05-21 22:15:50 +0000], [], [], [], [], [], [], []]

用于假设的AppointmentObject

extension Date {

    var month: Int {
        return Calendar.current.component(.month, from: self)
    }

}

// some random arbitrary dates
let appointments = [AppointmentObject(), AppointmentObject(), AppointmentObject()]
// the desired format
var sortedAppointmentsByFromMonth: [[AppointmentObject]] = []

// a filter to filter months by a given integer, you could also pull rawDates out of the equation here, to make it pure functional
let filterFromDatesByMonth = { month in appointments.filter { $0.from.month == month } }
// loop through the months in a calendar and for every month filter the dates and append them to the array
(1...12).forEach { sortedAppointmentsByFromMonth.append(filterFromDatesByMonth($0)) }

<强>替代

不是您问题的直接答案,但也许是您问题的可行解决方案。许多人,正直地指出了Dictionary阶级的存在。使用上面提到的Date扩展名,您也可以这样做:

Dictionary(grouping: rawDates) {$0.month}

输出

您的密钥现在是月份指标(5可能和3月3日)

[5: [2021-05-21 22:46:44 +0000], 3: [2018-03-21 13:00:04 +0000, 2018-03-22 16:46:44 +0000]]