2010-10-01 77 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 
} 
相关问题