How to add a number of weeks to an NSDate?

前端 未结 4 1673
一生所求
一生所求 2021-01-18 03:31

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

(NSDate *)dateByAddin         


        
4条回答
  •  生来不讨喜
    2021-01-18 04:19

    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];
    

提交回复
热议问题