问题描述
我是iPhone开发者的新手,
I am new to iPhone developer,
我想比较两个日期,第一个日期将来自数据库let say, newDate
,第二个是今天的日期,
i want to compare two Dates, first date will come from Database let say, newDate
and second is todays date,
如果今天大于 newDate
这是我的代码段,
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");
}
但是崩溃,并且编译时也会在此显示警告 [today compare:newDate]
but it crashes, and while compiling it also shows me warning here [today compare:newDate]
任何帮助将不胜感激。 $ b
推荐答案
问题是,你要比较字符串和日期。如果你看看 newDate
,你会看到它的 NSString
而不是 NSDate
。如果在 NSDate
上使用 compare:
方法,两个对象必须 NSDate
的。看看你的代码,看起来
st
是 NSDate
对应于 newDate
(虽然你的命名看起来有点奇怪),尝试今天
而不是 newDate
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
这篇关于比较两个NSDates在iPhone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!