Compare two NSDates in iPhone

给你一囗甜甜゛ 提交于 2019-12-11 00:53:24

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/11412852/compare-two-nsdates-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!