iOS获取当前日期的前n个月或后n个月时间

很简单,记录一下

- (NSString *)beforeDate:(NSInteger)n {
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *nowDateStr = [formatter stringFromDate:currentDate];
    NSLog(@"当前日期:%@",nowDateStr);
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    //    [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期,month day 类推
    [lastMonthComps setMonth:n];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    NSString *beforeDateStr = [formatter stringFromDate:newdate];
    
    return beforeDateStr;
}

你可能感兴趣的:(iOS获取当前日期的前n个月或后n个月时间)