Something does not add up.
I need to know how many days are there until Dec 21, 2012
NSDateFormatter *df= [[NSDateFormatter alloc] init];
NSDate *today = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
NSDate *dec21 = [[NSDate alloc] init];
dec21 = [df dateFromString:@"2012-12-21"];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:today
toDate:dec21 options:0];
NSInteger days = [components day];
NSInteger months = [components month];
NSString *result = [[NSString alloc] initWithFormat:@"About %d months and %d days left", months, days];
This code suggests there is still 129 months remaining.
What am i missing?
Your date formatter does not have a format set, so it is not returning an NSDate of 21st December. Add the following line after you have created the formatter:
And you’re set, until your next problem, which is that the result now says:
You need to include the years as well and add that to the months figure to get an actual time left if you are only going to count in months and days.