我目前有以下代码:
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对象的扩展。
我需要做同样的事情,但是让日历返回我从星期一开始而不是星期日的星期几。
答案 0 :(得分:4)
您只需要使用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"]