iOS獲取某個日期后n個月的日期
一、給一個時間姑蓝,給一個數(shù)鹅心,正數(shù)是以后n個月,負數(shù)是前n個月纺荧;
-(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month
{
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setMonth:month];
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0];
return mDate;
}
二旭愧、設置你需要增加或減少的年、月虐秋、日即可獲得新的日期榕茧,上述的表示獲取mydate日期前一個月的日期,如果該成+1客给,則是一個月以后的日期用押,以此類推都可以計算。
- (NSDate *)getLaterDateFromDate:(NSDate *)date withYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = nil;
comps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
NSDateComponents *adcomps = [[NSDateComponents alloc] init];
[adcomps setYear:year];
[adcomps setMonth:month];
[adcomps setDay:day];
NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:date options:0];
return newdate;
}
補充 : 將時間戳轉(zhuǎn)換為 NSDate
NSDate *date = [self getLaterDateFromDate:[NSDate dateWithTimeIntervalSince1970:[now_time integerValue] withYear:3 month:0 day:0];
補充 :將NSDate轉(zhuǎn)換為 字符串日期格式
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSString *dateStr = [formatter stringFromDate:date];
推薦文章 : https://blog.csdn.net/sqc3375177/article/details/53608867