服务器之家

服务器之家 > 正文

iOS获取某个日期后n个月的日期

时间:2021-03-25 15:30     来源/作者:SUPER_F

一、给一个时间,给一个数,正数是以后n个月,负数是前n个月;

?
1
2
3
4
5
6
7
8
-(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month
{
  NSDateComponents *comps = [[NSDateComponents alloc] init];
  [comps setMonth:month];
  NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0];
  return mDate;
}

二、设置你需要增加或减少的年、月、日即可获得新的日期,上述的表示获取mydate日期前一个月的日期,如果该成+1,则是一个月以后的日期,以此类推都可以计算。

?
1
2
3
4
5
6
7
8
9
10
11
- (NSDate *)getLaterDateFromDate:(NSDate *)date withYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
  NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  NSDateComponents *comps = nil;
  comps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
  NSDateComponents *adcomps = [[NSDateComponents alloc] init];
  [adcomps setYear:year];
  [adcomps setMonth:month];
  [adcomps setDay:day];
  NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:date options:0];
  return newdate;
}

总结

以上所述是小编给大家介绍的iOS获取某个日期后n个月的日期,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://www.cnblogs.com/SUPER-F/p/7298548.html

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部