2

I am new to iPhone developer,

i want to compare two Dates, first date will come from Database let say, newDate and second is todays date,

if today is greater then newDate then i want to display alert.

Here is my code snippet,

NSString *newDate = [formatter stringFromDate:st];
NSDate *today=[[NSDate alloc]init];

if ([today compare:newDate] == NSOrderedDescending)
{
    NSLog(@"today is later than newDate");        
}
else if ([today compare:newDate] == NSOrderedAscending)
{
    NSLog(@"today is earlier than newDate");        
}
else
{
    NSLog(@"dates are the same");        
}

but it crashes, and while compiling it also shows me warning here [today compare:newDate]

Any help will be appreciated.

Atulkumar V. Jain
  • 5,102
  • 9
  • 44
  • 61
Krunal
  • 6,440
  • 21
  • 91
  • 155

2 Answers2

6

The problem is, that you are comparing strings and dates. If you look at newDate, you will see that its a NSString and not a NSDate. If you use the compare: method on NSDate, both objects have to be NSDate's. Looking at your code, it looks like st is the NSDate corresponding to newDate (although your naming seems a bit odd), try today with it instead of newDate

JustSid
  • 25,168
  • 7
  • 79
  • 97
-1

You are trying to compare a date object with a string. You need to compare to date object.

[today compare:newDate] == NSOrderedDescending)

newDate should be a NSDate instance. I have done this and its working.

Atulkumar V. Jain
  • 5,102
  • 9
  • 44
  • 61
iamsult
  • 1,581
  • 1
  • 15
  • 21