我写了一个Date
扩展名,它返回给定日期(周一计算为第一天)的一周的第一天。但是,它过早地返回一个星期一。这是我的代码:
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
。
有人可以帮我理解为什么我的代码过早地返回一周的日期吗?
答案 0 :(得分:1)
应将日历计算添加到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
此外,您的要求并不完全清楚。在欧洲,星期一是本周的第一天。在北美,它是星期天。答案假设你总是想要星期一。