views:

123

answers:

2

Hi, how can I compare two dates return number of days. Ex: Missing X days of the Cup. look my code.

  NSDateFormatter *df = [[NSDateFormatter alloc]init];  
  [df setDateFormat:@"d MMMM,yyyy"];  
  NSDate *date1 = [df dateFromString:@"11-05-2010"];  
  NSDate *date2 = [df dateFromString:@"11-06-2010"];  
  NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];  
  //int days = (int)interval / 30;  
  //int months = (interval - (months/30)) / 30;  
  NSString *timeDiff = [NSString stringWithFormat:@"%dMissing%d days of the Cup",date1,date2, fabs(interval)];  

  label.text = timeDiff; // output (Missing X days of the Cup)  
+2  A: 

From Apple's example, basically use an NSCalendar:

NSDate * date1 = <however you initialize this>;
NSDate * date2 = <...>;

NSCalendar *gregorian = [[NSCalendar alloc]
                 initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                          fromDate:date1
                                          toDate:date2 options:0];

NSInteger months = [components month];
NSInteger days = [components day];
darelf
OP will also need to change date format to @"MM-dd-yyyy".
DyingCactus
I missed that the first time around. That's probably why he wasn't getting what he wanted.
darelf
A: 

Hi darelf, I done this but dont work. I changed date to string and compared two string and the return is null.

Thanks for all.

Dans Edu
Dans, you should comment on darelf's answer instead of adding an answer but: darelf's answer should work but you also need to change [df setDateFormat:@"d MMMM,yyyy"]; to [df setDateFormat:@"MM-dd-yyyy"]; because that's the format your date strings are in.
DyingCactus
Sorry, DyingCactus.Thank's allI finally finish, I used int months = [components month] int days = [components day] in place NSInteger months = [components month];NSInteger days = [components day];
Dans Edu