当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS获取某个日期后n个月的日期

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

青春梦工厂,中外励志故事,秋香网

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

-(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,则是一个月以后的日期,以此类推都可以计算。

- (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个月的日期,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网