您的位置:首页 > 移动开发 > IOS开发

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

2017-02-06 00:00 417 查看
通过传入year 和 month 和 day 得出currentTime 的前几天 前几月 钱

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

//得到当前的时间

//NSDate * mydate = [NSDate date];

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

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

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

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

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

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

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: