NSDateComponents weekOfYear returns wrong date

2020-02-13 05:03发布

问题:

so i am making a basic week picker, where you can pick a week number and year, and get the corresponding date from the weeks startpoint.

A basic test scenario

let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.year = 2015
components.weekOfYear = 15
print(calendar.dateFromComponents(components)!)

You can see, that i set the wanted year to 2015 and the wanted week to 15, but the result i get is: "2014-12-31 23:00:00 +0000"

... and thats really gets me hanging. No matter what week and year i choose, it will always be off and in december.

Thank you in advance for your help.

回答1:

weekOfYear works in conjunction with yearForWeekOfYear:

let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()

components.yearForWeekOfYear = 2015
components.weekOfYear = 15

print(calendar.dateFromComponents(components)!)
// 2015-04-05 22:00:00 +0000

Update for Swift 3 and later:

let calendar = Calendar.current
var components = DateComponents()

components.yearForWeekOfYear = 2015
components.weekOfYear = 15

print(calendar.date(from: components)!)