Modifying NSDate to represent 1 month from today

后端 未结 5 499
夕颜
夕颜 2021-01-31 11:07

I\'m adding repeating events to a Cocoa app I\'m working on. I have repeat every day and week fine because I can define these mathematically (3600*24*7 = 1 week). I use the foll

5条回答
  •  青春惊慌失措
    2021-01-31 11:36

    Use NSCalender, NSDateComponents and NSDate:

    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    components.month = 1;
    NSDate *oneMonthFromNow = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:[NSDate date] options:0];
    

    Just set the different properties of components to get different periods of time (e.g. 3 months, 6 months etc).

    Note: Depending on the context, you may want to use [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease] instead of [NSCalendar currentCalendar], if by "1 month" you mean "1 month on the Gregorian calendar".

提交回复
热议问题