Search code examples
swiftnscalendarnsdatecomponentsweekday

Getting weird date from NSCalendar.dateFromComponents


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?


Solution

  • 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.