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)
To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months. For the leftover period, work out the number of days.
To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered.
In the Select Specific Cells dialog box, select Cell in the Selection type section, select Greater than and enter the compared date in the box under Specific type section, and finally click OK or Apply button. Then the cells with dates which are greater than the specified date are selected immediately.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With