Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate adding a month the right way, clipping if previous month had more days

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

like image 848
Peter Lapisu Avatar asked Feb 16 '23 08:02

Peter Lapisu


1 Answers

That's what dateByAddingComponents is 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];
}
like image 67
Martin R Avatar answered May 09 '23 08:05

Martin R