iOS开发之得到当前时间的前几天,几个月,几年

经过传入year 和 month 和 day   得出currentTime 的前几天 前几月 钱component

-(NSDate *)beforYear:(NSInteger)year andBeforMonth:(NSInteger)month andBeforDay:(NSInteger)day andCurrentTime:(NSDate *)currentTime{orm

    

    //获得当前的时间对象

    //NSDate * mydate = [NSDate date];字符串

    

//    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];string

//    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"];it

//        NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];io

//        NSLog(@"---当前的时间的字符串 =%@",currentDateStr);date

    

    

    

//    先定义一个遵循某个历法的日历对象 (历法就是 推算日月星辰之运行以定岁时节候的方法 就当作日历好了)方法

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];im

    

   NSDateComponents *comps = nil;

     comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:currentTime];

    

    NSDateComponents *adcomps = [[NSDateComponents alloc] init];

    

    [adcomps setYear:year];

    

    [adcomps setMonth:month];

    

    [adcomps setDay:day];

    

    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:currentTime options:0];

    

//    NSString *beforDate = [dateFormatter stringFromDate:newdate];

//    NSLog(@"---前2年 =%@",beforDate);

    

    return newdate;

}

相关文章
相关标签/搜索