0

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!

Maulik
  • 19,348
  • 14
  • 82
  • 137
Tyrone Prude
  • 362
  • 7
  • 19
  • 6
    Why do people always write `[NSString stringWithFormat:@"%@", otherString]`, `[NSString stringWithString:otherString]` and similar **superfluous, processortime-wasting** calls? –  Oct 02 '12 at 14:59
  • @H2CO3 good call, man. I just found out I have a couple of these myself xD – Cashew Oct 02 '12 at 15:09

2 Answers2

2

You could use NSDate compare function

if([firstDate compare:secondUpdate] == NSOrderedAscending){
       //This will return YES if secondUpdate is the recent date between the two dates
}

NSOrderedAscending is a constant of NSComparisonResult Here are the other constants you could compare to:

enum {
 NSOrderedAscending = -1,
 NSOrderedSame,
 NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
KarenAnne
  • 2,764
  • 1
  • 28
  • 21
1

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:]).

g_fred
  • 5,878
  • 3
  • 28
  • 36