2010-10-01 89 views

回答

132

我所知道的最簡單的方法是:

if([firstDate timeIntervalSinceDate:secondDate] > 0) { 

其他的答案涵蓋比較:,想添加一些香精;) 。

+3

聰明的想法:) +1 – lukya 2010-10-01 12:59:50

+1

比用戶簡單得多NSDate比較:做得好! – 2013-06-09 09:40:47

+0

是的,謝謝。 +1 – fnc12 2015-02-02 08:28:42

28

要比較日期使用-compare:方法:

返回值如果:

  • 接收機和anotherDate是 恰好彼此相等, NSOrderedSame
  • 接收機是後面在 時間比另一個日期, NSOrderedDesc結束
  • 接收器在時間上早於 , NSOrderedAscending
11

當你有NSDates

NSDate *datStartDate = [NSDate dateWithString:@"2010-10-01 03:00:00 +0900"]; 
NSDate *datEndDate = [NSDate dateWithString:@"2010-10-01 04:00:00 +0900"]; 

if (([datStartDate compare:datEndDate]) == NSOrderedDescending) { 
    ... 
} 
+0

構建字符串以「自然語言」現在已經完全過時,這將不會編譯。 – Lewis42 2017-02-01 14:36:02

17

怎樣......

if ([datStartDate earlierDate: datEndDate] == datStartDate) { 
    // datStartDate is earlier 
} else { 
    // datEndDate is earlier 
} 
+0

非常感謝:) – Supertecnoboff 2016-06-29 10:04:41

2

斯威夫特2版接受的答案的:

if firstDate.timeIntervalSinceDate(secondDate) > 0 { 
    // firstDate is greater (further in the future) than secondDate 
} 
相關問題