繁体   English   中英

比较iPhone中的两个NSDate

[英]Compare two NSDates in iPhone

我是iPhone开发人员的新手,

我想比较两个日期,第一个日期将来自数据库, newDate ,第二个是今天的日期,

如果今天更大,则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]

任何帮助将不胜感激。

问题是,您正在比较字符串和日期。 如果查看newDate ,将看到它是NSString而不是NSDate 如果在NSDate上使用compare:方法,则两个对象都必须是NSDate的。 查看您的代码,看起来st是对应于newDateNSDate (尽管您的命名似乎有些奇怪), today尝试使用它而不是newDate

您正在尝试将日期对象与字符串进行比较。 您需要比较日期对象。

[today compare:newDate] == NSOrderedDescending)

newDate应该是一个NSDate实例。 我已经完成了它及其工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM