Search code examples
iosobjective-cios8nsdatensdatecomponents

How to add a number of weeks to an NSDate?


I have in the past used the below function to add on a specific time interval using NSDateComponents to an existing date.

(NSDate *)dateByAddingComponents:(NSDateComponents *)comps
                          toDate:(NSDate *)date
                         options:(NSCalendarOptions)opts

From iOS8 the week value is deprecated for NSDateComponents, which means I can't achieve what I want to do: generate a new NSDate by adding a certain number of weeks to a given NSDate.

Any help would be greatly appreciated.


Solution

  • Update: As Zaph said in his answer, Apple actually recommends using weekOfYear or weekOfMonth instead of the answer I provided. View Zaph's answer for details.


    You'll probably quickly realize that you're overthinking it, but here's how you can add a certain number of weeks to a date even though the week value's been deprecated, ex:

    NSDateComponents *comp = [NSDateComponents new];
    int numberOfDaysInAWeek = 7;
    int weeks = 3; // <-- this example adds 3 weeks
    comp.day = weeks * numberOfDaysInAWeek;
    
    NSDate *date = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0];