iOS-计算距离当前时间的前几天,几个月,几年

//得到当前的时间 
NSDate * mydate = [NSDate date];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
DebugLog(@"---当前的时间的字符串 =%@",currentDateStr); 
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 
NSDateComponents *comps = nil; 
comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:mydate]; 
NSDateComponents *adcomps = [[NSDateComponents alloc] init];
[adcomps setYear:0]; 
[adcomps setMonth:-2]; 
[adcomps setDay:0];
NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0]; NSString *beforDate = [dateFormatter stringFromDate:newdate]; 
DebugLog(@"---前两个月 =%@",beforDate);
--------------------- 

摘自:https://blog.csdn.net/weixin_34009794/article/details/87384045

你可能感兴趣的:(iOS-计算距离当前时间的前几天,几个月,几年)