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.
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.