NSDate adds the month in the right way, cutting off if there were more days in the previous month

I use this method to add a 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 in the previous month in the independent NSDate there were more days than on the first day of the next month, it jumps, for example

June has 31 => I - June 31 Calling this sets the date to 1.August as July has 30 days

How to do it right? I thought it should behave "right" and the clip at the end of the month

+4
source share
2 answers

What dateByAddingComponents for:

 - (NSDate *)sameDateByAddingMonths:(NSInteger)addMonths { NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [[NSDateComponents alloc] init]; [components setMonth:addMonths]; return [calendar dateByAddingComponents:components toDate:self options:0]; } 
+8
source

You can use this method to solve the problem, here I add 18 months to the date:

 +(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; } 
0
source

Source: https://habr.com/ru/post/1484633/


All Articles