如何在iOS中获取某个日期后n个月的日期
更新:HHH   时间:2023-1-8


本篇文章给大家分享的是有关如何在iOS中获取某个日期后n个月的日期,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

一、给一个时间,给一个数,正数是以后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个月的日期,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注天达云行业资讯频道。

返回移动开发教程...