Search code examples
iphoneiosnsdatensdateformatternsdatepicker

Compare two strings like date


Need to compare two variables of type NSDate.    One is the current date and the other is user selected date.

The user selects the date :

UIDatePicker *datePicker;   // declared in h file

-(void)dateChange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd-MM-yyy"];
dateLabel.text = [NSString stringWithFormat:@"%@", [df stringFromDate:datePicker.date]];

userDebtInfo.duration = dateLabel.text;}

Validation Method :

-(IBAction) validation:(id)sender{
NSDate *today = [NSDate date];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSString *dateString = [dateFormat stringFromDate:today];

[dateFormat release];

 if ((userDebtInfo.debt_code == userTmp.debt_code) && ([userDebtInfo.duration compare:dateString]== NSOrderedDescending)))
            [bl updateUserMoneyValidation:userDebtInfo];  
 else
      [bl saveUserMoneyValidation:userDebtInfo];}

I have tested and is comparing two strings. Can someone help me with some advice about this condition, please? I want to compare if the selected date is after the current date to do insert or update the database.

   Thank you!


Solution

  • If you already have two objects of type NSDate, you could use one of the NSDate comparison methods. For instance [NSDate compare:] which returns a NSComparisonResult (this is the same enum as returned by [NSString compare:]).