我的目标是获取星期的开始日期和结束日期。所以我发现:
https://stackoverflow.com/a/46402722/4757272,这是一个非常简洁的解决方案。但是,我有一些问题。试试看,当我查看日历时,名为sunday
的变量实际上是一个星期六,那确实很令人不安,但是真正令人不安的部分出现了:
extension Date {
var startOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 1, to: sunday)
}
var endOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 7, to: sunday)
}
}
dump(Date().startOfWeek)
dump(Date().endOfWeek)
如您所见,我可以打印结果,并且在操场上也可以像在游乐场一样流畅地显示结果。但是它们是不同的日期。.所以我应该依靠哪一个?