比较2 NSDate

时间:2011-11-14 10:40:44

标签: ios xcode nsdate

我有2个NSDate个对象,第一个对象设置为提前一个月,并且seconed设置为今天。 我想检查今天是否在(更大)之后是未来一个月的对象。

我该怎么做?

4 个答案:

答案 0 :(得分:11)

您可以使用NSDate's compare method。例如:

switch ([dateOne compare:dateTwo]) {
case NSOrderedAscending:
    // dateOne is earlier in time than dateTwo
    break;
case NSOrderedSame:
    // The dates are the same
    break;
case NSOrderedDescending:
    // dateOne is later in time than dateTwo
    break;
}

答案 1 :(得分:4)

阅读Date and Time Programming Guide很多日期&时间概念(以及Cocoa如何处理它们)在这里详细解释,非常值得一读。

此外,在NSDate class Reference, you can find a dedicated section"比较日期"用于比较两个日期的所有方法。因此,您应该使用完全回答您问题的laterDate:earlierDate:方法。您也可以使用timeIntervalSinceDate:方法并检查返回时间间隔的符号(再次参阅相关文档)

一般来说,不要犹豫阅读文档,因为一切已经详细解释了,因为您可以看到这些链接< / em>的

答案 2 :(得分:2)

NSDate* earlierDate = [aDate earlierDate:anotherDate];

返回值 接收器和anotherDate的早期,使用timeIntervalSinceDate确定:如果接收者和anotherDate代表相同的日期,则返回接收者。

答案 3 :(得分:0)

转到此链接:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

其他明智的做法是将您的日期转换为双倍并进行比较。所有相关的功能都在这个链接中。