Search code examples
iphoneobjective-ciosxcodensdate

How to tell the amount of days from now until an NSDate?


How can I tell the amount of days from now until the date specified in my app? Here is what I have so far, but it comes up with "-30" every time, no matter what the date is:

NSDate * selected = [DatePicker date];
NSString * date = [selected description];

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit 
                                                              fromDate:DatePicker.date];

CalLabel1.text = [NSString stringWithFormat:@"%d", [components day]];

NSDateFormatter *temp = [[NSDateFormatter alloc] init];
[temp setDateFormat:@"dd/MM/yyyy"];
NSDate *stDt = [temp dateFromString:[temp stringFromDate:[NSDate date]]];
NSDate *endDt =  [temp dateFromString:[temp stringFromDate:[NSString stringWithFormat:@"%d", [components date]]]];
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:stDt  toDate:endDt  options:0];
int days = [comps day];

NSLog(@"%i", [comps day]);

Solution

  • NSDate * selected = [DatePicker date];
    NSCalendar *gregorian = [[NSCalendar alloc] 
                              initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components: NSDayCalendarUnit 
                                           fromDate: [NSDate date]  
                                             toDate: selected  
                                            options: 0];
    int days = [comps day];
    
    NSLog(@"%i", [comps day]);
    

    This calculates the number of days between now and the selected date. All your messing around with the date formatter was wrong and not necessary.