4

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
  • Your code adds 2013 years, 11 months, ... to the current date.
    – Martin R
    Oct 12, 2013 at 17:16

2 Answers 2

13

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);
0
-1
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.