iOS one month from current Date.

柔情痞子 提交于 2019-12-19 08:54:24

问题


I'm trying to get one month from the current date.

Below is what I have and it is returning: 4027-09-24 16:59:00 +0000. currentDate is right. What's going on?

// Get todays date to set the monthly subscription expiration date
NSDate *currentDate = [NSDate date];
NSLog(@"Current Date = %@", currentDate);
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit fromDate:currentDate];
dateComponents.month = dateComponents.month + 1;
NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(@"Date = %@", currentDatePlus1Month);

回答1:


Try this instead:

// Get todays date to set the monthly subscription expiration date
NSDate *currentDate = [NSDate date];
NSLog(@"Current Date = %@", currentDate);

NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.month = 1;

NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(@"Date = %@", currentDatePlus1Month);



回答2:


NSDate *currentDate = [NSDate date];

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate]; 
  // Get necessary date components

[components month]; //gives you month

[components day]; //gives you day

[components year]; //gives you year


来源:https://stackoverflow.com/questions/19336836/ios-one-month-from-current-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!