1

I am trying to get a date from the component's year, week, and dayOfWeek, but I am getting weird dates from the above mentioned function. Here is what I do:

let calendar = NSCalendar(identifier: NSCalendarIdentifierISO8601)
let components = NSDateComponents()
components.weekday = 1
components.weekOfYear = 16
components.yearForWeekOfYear = 2016
let dateKW = calendar?.dateFromComponents(components)

The variable dateKW equals 24. April 2016. When I change the weekday to 2, I get 18. April 2016. Why is that the case? Shouldn't the first day be 17. April 2016?

1 Answer 1

3

In the Gregorian calendar, weekday units range from 1=Sunday, 2=Monday, ..., to 7=Saturday. If the first weekday in your locale is Monday (like for example in Germany), then the 18th calendar week in 2016 ranges from April 18 (Monday) to April 24 (Sunday).

Therefore asking for the Sunday in week #16

components.weekday = 1
components.weekOfYear = 16
components.yearForWeekOfYear = 2016

correctly returns April 24, 2016. If you need the first day of that week then set

components.weekday = calendar.firstWeekday

or simply don't set components.weekday at all.

1
  • oh ok so it is more like an enum with 1=sunday ... 7=saturday alrighty, now i get it, thanks. I am getting the weekday, weekofyear and Year data from another source and i have to display them as the right days. And yes i am in germany. My solution is now that is add 1 to my weekday and fortunately it seems to return the right date for me. Commented Sep 19, 2016 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.