How to add a number of weeks to an NSDate?

前端 未结 4 1623
一生所求
一生所求 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:16

    Just use weekOfYear:

    Apple docs for NSDateComponents week:

    Deprecation Statement
    Use weekOfYear or weekOfMonth instead, depending on what you intend.

    NSDate *date = [NSDate date];
    NSDateComponents *comp = [NSDateComponents new];
    comp.weekOfYear = 3;
    NSDate *date1 = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0];
    NSLog(@"date:  %@", date);
    NSLog(@"date1: %@", date1);
    

    Output:

         
    date:  2015-01-13 04:06:26 +0000  
    date1: 2015-02-03 04:06:26 +0000
    

    If you use week you get this warning:

    'week' is deprecated: first deprecated in ... - Use weekOfMonth or weekOfYear, depending on which you mean

    When using the weekOfMonth or weekOfYear as a delta they work the same. Where they are different is when they are used to obtain the week number where you will get the week of the month with a range of 6 or the week of the year with a range of 53.

提交回复
热议问题