1 -(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month 2 3 { 4 5 NSDateComponents *comps = [[NSDateComponents alloc] init]; 6 7 [comps setMonth:month]; 8 9 NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 10 11 NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0]; 12 13 14 return mDate; 15 16 }
二、设置你需要增加或减少的年、月、日即可获得新的日期,上述的表示获取mydate日期前一个月的日期,如果该成+1,则是一个月以后的日期,以此类推都可以计算。
1 - (NSDate *)getLaterDateFromDate:(NSDate *)date withYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day { 2 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 3 4 NSDateComponents *comps = nil; 5 6 comps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date]; 7 8 NSDateComponents *adcomps = [[NSDateComponents alloc] init]; 9 10 [adcomps setYear:year]; 11 12 [adcomps setMonth:month]; 13 14 [adcomps setDay:day]; 15 16 NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:date options:0]; 17 18 return newdate; 19 }