let calendar = Calendar.current var dateComponents = DateComponents() dateComponents.weekday = calendar.firstWeekday dateComponents.weekOfYear = 2 dateComponents.year = 2017 let startOfWeek = calendar.date(from: dateComponents) let endOfWeek = calendar.date(byAdding: .day,value: 6,to: startOfWeek!) let formatter = DateFormatter() formatter.dateStyle = .short print(formatter.string(from: startOfWeek!)) print(formatter.string(from: endOfWeek!))
打印:
1/8/17 1/14/17
改变代码:
dateComponents.weekOfYear = 1 dateComponents.year = 2017
打印:
12/31/17 1/6/18
为什么是12/31/17?
有谁告诉我?非常感谢.
解决方法
当我使用.full样式打印日期时,我会在2017年12月31日星期日的第一个日期,但这显然是错误的,因为12月31日是星期四.
如果您想获得正确的日期,请使用yearForWeekOfYear而不是year. Docs:
You can use the yearForWeekOfYear property with the weekOfYear and weekday properties to get the date corresponding to a particular weekday of a given week of a year. For example,the 6th day of the 53rd week of the year 2005 (ISO 2005-W53-6) corresponds to Sat 1 January 2005 on the Gregorian calendar.
另外,你可能有点顽皮而不听文档并使用weekOfYear = 54:
let calendar = Calendar.current var dateComponents = DateComponents() dateComponents.weekday = calendar.firstWeekday dateComponents.weekOfYear = 54 dateComponents.year = 2017 let startOfWeek = calendar.date(from: dateComponents) let endOfWeek = calendar.date(byAdding: .day,to: startOfWeek!) let formatter = DateFormatter() formatter.dateStyle = .short print(formatter.string(from: startOfWeek!)) print(formatter.string(from: endOfWeek!))
这打印:
1/1/17 1/7/17
巧合的是,正确的日期.