Modifying NSDate to represent 1 month from today

后端 未结 5 468
夕颜
夕颜 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 12:02

    (Almost the same as this question.)

    From the documentation:

    Use of NSCalendarDate strongly discouraged. It is not deprecated yet, however it may be in the next major OS release after Mac OS X v10.5. For calendrical calculations, you should use suitable combinations of NSCalendar, NSDate, and NSDateComponents, as described in Calendars in Dates and Times Programming Topics for Cocoa.

    Following that advice:

    NSDate *today = [NSDate date];
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = 1;
    NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
    [components release];
    
    NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth];
    
    NSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today];
    
    nextMonthComponents.day = todayDayComponents.day;
    NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];
    
    [gregorian release];
    

    There may be a more direct or efficient implementation, but this should be accurate and should point in the right direction.

提交回复
热议问题