Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare two dates, return a number of days

Tags:

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)   
like image 614
Dans Avatar asked Mar 30 '10 19:03

Dans


People also ask

How do I calculate the number of days between two dates?

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.

How do I calculate the number of days between two dates in Excel?

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.

How do I compare 3 dates in Excel?

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.


1 Answers

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]; 
like image 186
darelf Avatar answered Sep 20 '22 03:09

darelf