如何在swift中获得本周的开始和结束? 这是我的代码
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)
}
}
我这样打电话
let startWeek = Date().startOfWeek
let endWeek = Date().endOfWeek
print(startWeek!)
print(endWeek!)
var dateFormat1 = DateFormatter()
dateFormat1.dateFormat = "dd-MM-yy"
let startWeek2 = dateFormat1.string(from: startWeek!)
var dateFormat12 = DateFormatter()
dateFormat12.dateFormat = "dd-MM-yy"
let endWeek2 = dateFormat12.string(from: endWeek!)
print(startWeek2)
print(endWeek2)
和输出
2017-09-24 18:30:00 +0000
2017-09-30 18:30:00 +0000
25-09-17
01-10-17
答案 0 :(得分:6)
这是Swift 3版本: -
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)
}
}
您可以像这样获得周开始日期和结束日期:
let startWeek = Date().startOfWeek
let endWeek = Date().endOfWeek
print(startWeek ?? "not found start date")
print(endWeek ?? "not found end date")
答案 1 :(得分:0)
您的代码工作正常。如果要在Playground中运行代码,则可以看到实际的Date
对象而不是String表示。即使你没有指定DateFormatter
,在做print(Date())
时,Swift使用DateFormatter
打印Date
个对象,因此该值将是相对时间而不是Date
对象提供的绝对时间点。
在游乐场中,您可以看到实际的startOfWeek
为"Sep 25, 2017 at 12:00 AM"
,而endOfWeek
为"Oct 1, 2017 at 12:00 AM"
,这是本周的正确值。
请勿使用print(Date())
来检查Date
个对象的正确性,因为正如您所看到的,由于使用了基础DateFormatter
,它会产生意外结果。< / p>