Search code examples
iosswiftnsdateswift2nscalendar

Adding a day to a date with NSCalendar


I'm trying to add a day to another (it works perfectly until I saw something).

For the week 6 in 2016 (starting the 30th of january), if I had a day to this date, it shows me the 31st of december 2015.

Can you explain me what I'm doing wrong ?

Here is the code (you can put it in a playground):

let weekToDisplay = 6
let yearToDisplay = 2016

let calendar = NSCalendar.currentCalendar()
let comp = NSDateComponents()
comp.weekday = calendar.firstWeekday
comp.weekOfYear = weekToDisplay
comp.year = yearToDisplay

let dateToIncrement = calendar.dateFromComponents(comp)! // "Jan 31, 2016, 12:00 AM
var incrementedDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateToIncrement, options: NSCalendarOptions.WrapComponents)! // "Jan 1, 2016, 12:00 AM"

print(dateToIncrement) // "2016-01-30 23:00:00 +0000\n"
print(incrementedDate) // "2015-12-31 23:00:00 +0000\n"

Last thing, when you print the date, it's not the same as showed in the playground when executing that particular line of code, why ? (see the comments)


Solution

  • Your issue is the option to wrap the date components. You don't want that. Simply do:

    let weekToDisplay = 6
    let yearToDisplay = 2016
    
    let calendar = NSCalendar.currentCalendar()
    let comp = NSDateComponents()
    comp.weekday = calendar.firstWeekday
    comp.weekOfYear = weekToDisplay
    comp.year = yearToDisplay
    
    let dateToIncrement = calendar.dateFromComponents(comp)! // "Jan 31, 2016, 12:00 AM
    var incrementedDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateToIncrement, options: [])! // "Jan 1, 2016, 12:00 AM"
    
    print(dateToIncrement)
    print(incrementedDate)