一、給一個時間,給一個數,正數是以後n個月,負數是前n個月; 1 -(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month 2 3 { 4 5 NSDateComponents *comps = ...
一、給一個時間,給一個數,正數是以後n個月,負數是前n個月;
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 }