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;

}

相關文章
相關標籤/搜索