参见英文答案 How do I find the beginning of the week from an NSDate?4个 How to get Monday’s date of the current week in swift7个 如何在swift中获得本周的开始和结束? 这是我的代码 extension Date { var startOfWee
> How to get Monday’s date of the current week in swift 7个
如何在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你的代码工作得非常好.如果要在Playground中运行代码,则可以看到实际的Date对象而不是String表示.即使您没有指定DateFormatter,在执行print(Date())时,Swift使用DateFormatter来打印Date对象,因此该值将是相对时间而不是由提供的绝对时间点.日期对象.
在游乐场中,您可以看到实际的startOfWeek是“2017年9月25日上午12:00”,而endOfWeek是“2017年10月1日上午12:00”,这是本周的正确值.
不要使用print(Date())来检查Date对象的正确性,因为正如您所看到的,由于使用了基础DateFormatters,它将产生意外结果.