iphone - 如何比较两个 NSDates : Which is more recent?

我正在尝试实现 dropBox 同步,并且需要比较两个文件的日期。一个在我的 dropBox 帐户上,一个在我的 iPhone 上。

我想出了以下方法,但得到了意想不到的结果。我想在比较这两个日期时我做错了什么。我只是使用了 >

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了解更多详情。

https://stackoverflow.com/questions/5965044/

相关文章:

ios - 如何在 iOS 上找到最顶层的 View Controller

ios - Pod 安装停留在 "Setting up CocoaPods Master repo"

ios - 单个 UILabel 中的粗体和非粗体文本?

ios - 架构 i386 : _OBJC_CLASS_$_SKPSMTPMessage", 的 u

iphone - 如何使用使用 Interface Builder 创建的 nib 文件加载 UIV

objective-c - 为设备编译时出现 Apple Mach-O 链接器错误

objective-c - Xcode 6 中未创建 Swift 到 Objective-C hea

ios - Objective-C 中的自动引用计数不能防止或最小化什么样的泄漏?

iphone - iOS 7 导航栏文本和箭头颜色

ios - 不区分大小写的比较 NSString