Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

swift - NSDateComponents weekOfYear returns wrong date

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)!)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...