如何快速通过特定年份来获取一年中(星期六和星期日)的所有周末日期?

时间:2018-09-06 13:24:37

标签: swift

如何通过快速度过特定年份来获取所有周末日期(周六和周日)?举例来说,如果我经过2018年,它将返回[6/1/18]

1 个答案:

答案 0 :(得分:0)

您可以获取一年中的天数,使用compactMap遍历它们,检查每天是否在周末,如果返回正数,否则返回nil:

extension Date{
    var year: Int {
        return Calendar.current.component(.year, from: self)
    }
    var weekendsInSameYear: [Date] {
        return Calendar.current.range(of: .day, in: .year, for: self)?.compactMap {
            guard let date = DateComponents(calendar: .current, year: year, day: $0).date, Calendar.current.isDateInWeekend(date) else {
                return nil
            }
            return date
        } ?? []

    }
}

let dates = Date().weekendsInSameYear
for date in dates {
    print(date.description(with: .current))
}

//  "Saturday, January 6, 2018 at 12:00:00 AM Brasilia Summer Time"
//  "Sunday, January 7, 2018 at 12:00:00 AM Brasilia Summer Time"
//  "..."
//  "Saturday, December 29, 2018 at 12:00:00 AM Brasilia Summer Time"
//  "Sunday, December 30, 2018 at 12:00:00 AM Brasilia Summer Time"