NSDateComponents weekOfYear returns wrong date

蓝咒 提交于 2019-11-28 06:22:41

问题


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


来源:https://stackoverflow.com/questions/33767401/nsdatecomponents-weekofyear-returns-wrong-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!