我正在尝试实现 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.
最佳答案
假设有两个日期:
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 class documentation了解更多详情。
关于iphone - 如何比较两个 NSDates : Which is more recent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5965044/