一尘不染

获取从星期一开始的当前星期的日期数组

swift

我目前有此代码:

public var daysOfWeek: [Date]? {

    let calendar = Calendar.current

    let today = self
    let dayOfWeek = calendar.component(.weekday, from: today)
    if let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today){

        let days = (weekdays.lowerBound ..< weekdays.upperBound).compactMap {
            calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today)
        }
        return days
    }else{
        return nil
    }
}

这是Date对象的扩展。

我需要做同样的事情,但是让日历返回我从星期一开始而不是星期日的一周中的几天。


阅读 215

收藏
2020-07-07

共1个答案

一尘不染

您只需要使用iso8601日历获取一周中的第一天,其中第一个工作日为星期一,并添加0至6天。尝试这样:

extension Calendar {
    static let iso8601 = Calendar(identifier: .iso8601)
}
extension Date {
    var startOfWeek: Date {
        return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
    }
    var daysOfWeek: [Date] {
        let startOfWeek = self.startOfWeek
        return (0...6).compactMap{ Calendar.current.date(byAdding: .day, value: $0, to: startOfWeek)}
    }
}

Date().daysOfWeek  // ["Aug 13, 2018 at 12:00 AM", "Aug 14, 2018 at 12:00 AM", "Aug 15, 2018 at 12:00 AM", "Aug 16, 2018 at 12:00 AM", "Aug 17, 2018 at 12:00 AM", "Aug 18, 2018 at 12:00 AM", "Aug 19, 2018 at 12:00 AM"]
2020-07-07