swift – 一周中的第一天Date Extension

我写了一个日期扩展,它返回给定日期(周一计算为第一天)的一周的第一天.但是,它过早地返回一个星期一.这是我的代码:

extension Date {
    func startOfWeek() -> Date {
        var cal = Calendar.current
        var component = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
        cal.firstWeekday = 2
        return cal.date(from: component)!
    }
}

所以当我给它以下日期时:

let sampleDate = "2017-06-15 02:50:09 +0000"

let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
    if let date = formatter.date(from: sampleDate) {
        print(date.startOfWeek())
    }
}

2017-06-05 07:00:00 0000打印出来.

任何人都可以帮助我理解为什么我的代码过早地返回一周的日期?

最佳答案 应该将日历计算添加到Calendar对象(就像startOfDay(for :)).如果您坚持将其作为Date的扩展,您可以调整以下代码:

extension Calendar {
    func startOfWeek(for date: Date) -> Date {
        if self.component(.weekday, from: date) == 2 {
            return self.startOfDay(for: date)
        } else {
            let components = DateComponents(calendar: self, weekday: 2)
            return self.nextDate(after: date, matching: components, matchingPolicy: .nextTime, direction: .backward)!
        }
    }
}

// Test: 2017-06-15 02:50:09 in your **local time**
let date = DateComponents(calendar: .current, year: 2017, month: 6, day: 15, hour: 2, minute: 50, second: 9).date!

// My timezone is EDT
print(Calendar.current.startOfWeek(for: date)) // 2017-06-12 04:00:00 +0000

此外,您的要求并不十分清楚.在欧洲,星期一是本周的第一天.在北美,这是星期天.答案假设你总是想要星期一.

点赞