我使用此方法将月份添加到日期
- (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];
}
但是当前一个月在自我NSDate,有更多的日子,比在下个月的第一天跳跃,像
六月有31 =>自己是6月31日 调用此项,将日期设置为1. 8月,因为7月有30天
如何做到这一点?我认为这应该表现“正确”并在月末剪辑
答案 0 :(得分: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];
}
答案 1 :(得分: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; }