Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

swift - Get an Array of Dates of the current week starting on Monday

I have this code currently:

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

This is an extension of the Date object.

I need to do the same thing, but have the Calendar return me the days of the week starting with Monday and not Sunday.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You just need to get the first day of the week using iso8601 calendar where the first weekday is Monday and add from 0 to 6 days to it. Try like this:

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"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...