2013-06-04 92 views
-3

我想比較兩個日期一個人是否是新的還是舊的,我的日期是在以下格式:我如何比較兩個日期?

2013年6月3日9點30分35秒

(YYYY- MM-DD HH:MM:SS)

請給我一些想法,目前都是字符串格式?

那麼有可能轉換廣告檢查?

回答

1

試試這個

的NSString的NSDate

NSString *dateString = @"01-02-2010"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
// this is imporant - we set our input date format to match our input string 
// if format doesn't match you'll get nil from your string, so be careful 
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 
NSDate *dateFromString = [[NSDate alloc] init]; 
// voila! 
dateFromString = [dateFormatter dateFromString:dateString]; 
[dateFormatter release]; 

的NSDate轉換爲NSString的:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]]; 
NSLog(@"%@", strDate); 
[dateFormatter release]; 

請仔細閱讀本

enter link description here

if ([yourFirstDate compare:secondDate] == NSOrderedDescending) { 
    NSLog(@"yourFirstDate is later than secondDate");   

} else if ([yourFirstDate compare:secondDate] == NSOrderedAscending) { 
    NSLog(@"yourFirstDate is earlier than secondDate"); 

} else { 
    NSLog(@"dates are the same"); 

} 

一樣@DIVYU的鏈接

+0

你遺漏了關於比較的一點。 – Abizern

+0

謝謝,但我怎麼能比較? – Navi

+0

ok好work.let我試試這個 – Navi

2

使用dateFormatter將字符串轉換爲NSDate。 您可以檢查此鏈接這裏是你的問題好商量 How to compare two NSDates: Which is more recent?

+4

如果你想到一個問題是重複的,請註明它是一個重複的,而不是一個回答鏈接到其他問題和答案。 – Abizern

+0

好的,但我沒有看到任何標記重複的選項。 – Divyu

+1

這是關閉的鏈接。它給你選擇爲什麼你建議關閉。其中一個原因是它是重複的。您可以將鏈接粘貼到該副本中。 – Abizern