如何比较两个nsdate:哪个是最近的?

我试图实现dropBox同步,需要比较两个文件的日期。一个在我的dropBox账户上,一个在我的iPhone上。

我想出了以下方法,但我得到了意想不到的结果。我想我在比较这两个日期时做了一些根本性的错误。我只用了> <操作符,但我猜这是不行的,因为我比较两个NSDate字符串。开始吧:

NSLog(@"dB...lastModified: %@", dbObject.lastModifiedDate);
NSLog(@"iP...lastModified: %@", [self getDateOfLocalFile:@"NoteBook.txt"]);


if ([dbObject lastModifiedDate] < [self getDateOfLocalFile:@"NoteBook.txt"]) {
NSLog(@"...db is more up-to-date. Download in progress...");
[self DBdownload:@"NoteBook.txt"];
NSLog(@"Download complete.");
} else {
NSLog(@"...iP is more up-to-date. Upload in progress...");
[self DBupload:@"NoteBook.txt"];
NSLog(@"Upload complete.");
}

这给了我以下(随机&错误的)输出:

2011-05-11 14:20:54.413 NotePage[6918:207] dB...lastModified: 2011-05-11 13:18:25 +0000
2011-05-11 14:20:54.414 NotePage[6918:207] iP...lastModified: 2011-05-11 13:20:48 +0000
2011-05-11 14:20:54.415 NotePage[6918:207] ...db is more up-to-date.

或者这个恰好是正确的:

2011-05-11 14:20:25.097 NotePage[6903:207] dB...lastModified: 2011-05-11 13:18:25 +0000
2011-05-11 14:20:25.098 NotePage[6903:207] iP...lastModified: 2011-05-11 13:19:45 +0000
2011-05-11 14:20:25.099 NotePage[6903:207] ...iP is more up-to-date.
148182 次浏览

让我们假设两个日期:

NSDate *date1;
NSDate *date2;

下面的比较将告诉我们哪个更早/更晚/相同:

if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(@"date1 is earlier than date2");
} else {
NSLog(@"dates are the same");
}

更多细节请参考NSDate类文档

你应该使用:

- (NSComparisonResult)compare:(NSDate *)anotherDate

比较日期。objective C中没有运算符重载。

你想要使用NSDate compare:, laterDate:,早期日期:,或isEqualToDate:方法。使用<>运算符在这种情况下是比较指针,而不是日期

NSDate有一个比较函数。

compare:返回一个NSComparisonResult值,该值指示接收器和另一个给定日期的时间顺序。

(NSComparisonResult)compare:(NSDate *)anotherDate
< p > 参数: anotherDate 用来比较接收者的日期。 该值不能为nil。如果该值为nil,则该行为未定义,并且可能在Mac OS x的未来版本中更改

返回值:

  • 如果接收者和anotherDate完全相等,则NSOrderedSame .
  • 如果接收者晚于另一个日期,NSOrderedDescending
  • 如果接收者在时间上早于另一个日期,NSOrderedAscending
- (NSDate *)earlierDate:(NSDate *)anotherDate

这将返回较早的接收者和另一个日期。如果两者相同,则返回接收器。

我遇到过几乎相同的情况,但在我的情况下,我要检查是否天数不同

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *compDate = [cal components:NSDayCalendarUnit fromDate:fDate toDate:tDate options:0];
int numbersOfDaysDiff = [compDate day]+1; // do what ever comparison logic with this int.

当你需要以天/月/年为单位比较NSDate时非常有用

我试过了,希望对你有用

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int unitFlags =NSDayCalendarUnit;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *myDate; //= [[NSDate alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
myDate = [dateFormatter dateFromString:self.strPrevioisDate];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:myDate toDate:[NSDate date] options:0];
NSInteger day=[comps day];

比较NSDate对象的另一种简单方法是将它们转换为原始类型,这允许轻松使用'>' '<' '=='等

如。

if ([dateA timeIntervalSinceReferenceDate] > [dateB timeIntervalSinceReferenceDate]) {
//do stuff
}

timeIntervalSinceReferenceDate将日期转换为自引用日期(2001年1月1日,格林尼治时间)以来的秒数。由于timeIntervalSinceReferenceDate返回一个NSTimeInterval(它是一个双类型定义),我们可以使用基元比较器。

你也可以用这个方法比较两个日期

        switch ([currenttimestr  compare:endtimestr])
{
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;


}

一些日期工具,包括比较在英语,这是很好的:

#import <Foundation/Foundation.h>




@interface NSDate (Util)


-(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
-(BOOL) isLaterThan:(NSDate*)date;
-(BOOL) isEarlierThan:(NSDate*)date;
- (NSDate*) dateByAddingDays:(int)days;


@end

实现:

#import "NSDate+Util.h"




@implementation NSDate (Util)


-(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedAscending);
}


-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedDescending);
}
-(BOOL) isLaterThan:(NSDate*)date {
return ([self compare:date] == NSOrderedDescending);


}
-(BOOL) isEarlierThan:(NSDate*)date {
return ([self compare:date] == NSOrderedAscending);
}


- (NSDate *) dateByAddingDays:(int)days {
NSDate *retVal;
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:days];


NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
retVal = [gregorian dateByAddingComponents:components toDate:self options:0];
return retVal;
}


@end

为什么你们不使用这些NSDate比较方法呢:

- (NSDate *)earlierDate:(NSDate *)anotherDate;
- (NSDate *)laterDate:(NSDate *)anotherDate;

在Swift中,你可以重载现有的操作符:

func > (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}


func < (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}

然后,你可以直接将nsdate与<>==(已经支持)进行比较。

使用这个简单的函数进行日期比较

-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{


BOOL isTokonValid;


if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(@"date1 is later than date2");
isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(@"date1 is earlier than date2");
isTokonValid = NO;
} else {
isTokonValid = NO;
NSLog(@"dates are the same");
}


return isTokonValid;}