簡體   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