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

比眉伴天荒 2023-10-10 09:04 71阅读 0赞

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

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

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

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

转载于:https://www.cnblogs.com/SUPER-F/p/7298548.html

发表评论

表情:
评论列表 (有 0 条评论,71人围观)

还没有评论,来说两句吧...

相关阅读