Adarkas2302 Adarkas2302 - 1 year ago 70
Swift Question

Getting weird date from NSCalendar.dateFromComponents

I am trying to get a date from the

, and
, 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
to 2, I get 18. April 2016. Why is that the case? Shouldn't the first day be 17. April 2016?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download