4

I use this method for adding month to a date

- (NSDate *)sameDateByAddingMonths:(NSInteger)addMonths {

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents * components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self];
    [components setMonth:components.month + addMonths];

    return [calendar dateFromComponents:components];

}

But when the previous month in self NSDate, had more days, than it jumps on the first day next next month, like

June has 31 => self is June 31 Calling this, sets the date to 1.August, since July has 30 days

How to get this right? i thought this should behave "right" and clip on the end of month

4

2 回答 2

8

这就是dateByAddingComponents

- (NSDate *)sameDateByAddingMonths:(NSInteger)addMonths {

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setMonth:addMonths];

    return [calendar dateByAddingComponents:components toDate:self options:0];
}
于 2013-06-05T12:45:03.193 回答
0

您可以使用这样的方法来解决问题,这里我将 18 个月添加到日期:

+(NSDate *)addEighteenMonthsToDate:(NSDate *)startDate {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDate *newDate = [startDate copy];

newDate = [calendar dateByAddingUnit:NSCalendarUnitYear value:1 toDate:startDate options:0];

newDate = [calendar dateByAddingUnit:NSCalendarUnitMonth value:6 toDate:newDate options:0];

return newDate;  } 
于 2017-10-08T11:42:06.063 回答