如何比较iPhone中的两个日期?

时间:2011-03-25 06:31:29

标签: iphone objective-c cocoa-touch ios4

我想比较今天的日期和来自我的数据库的其他日期。 例如,2011-03-25将其与2011-02-25进行比较

如何在NSDateFormatter需要NSDdate数据类型的情况下格式化数据库日期?

6 个答案:

答案 0 :(得分:3)

Cocoa has couple of methods for this:

NSDate中的

- isEqualToDate:
- earlyDate:
- laterDate:
- 比较:

当你使用 - (NSComparisonResult)比较:(NSDate *)anotherDate时,你会得到其中一个:

The receiver and anotherDate are exactly equal to each other, NSOrderedSame
The receiver is later in time than anotherDate, NSOrderedDescending
The receiver is earlier in time than anotherDate, NSOrderedAscending.

更多阅读SO post

通过博客文章,有许多与日期相关的实用功能。

http://arstechnica.com/apple/guides/2010/03/how-to-real-world-dates-with-the-iphone-sdk.ars/2

答案 1 :(得分:1)

NSDate *date1 = [NSDate date];
NSDate *date2 = [NSDate date];

if ([date1 compare: date2]==NSOrderedAscending) {
    NSLog(@"YES");
}

答案 2 :(得分:0)

答案 3 :(得分:0)

如果您的日期类似于年 - 月 - 日,则可以比较字符串:

 if ([date1 compare:string2]==NSOrderedAscending) {
 } else if ([date1 compare:string2]== NSOrderedDescending) {
 } else {
 }

它会起作用,因为日期中的字段从最重要到较少,就像字符串比较一样。

答案 4 :(得分:0)

您可以使用NSDate compare:或timeIntervalSinceReferenceDate - 这将让您入门

答案 5 :(得分:0)

Swift

let date1 = NSDate() //some date
let date2 = NSDate() //another date

let firstDate = date1.earlierDate(date2)
let lastDate = date1.laterDate(date2)