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

标签 iphone objective-c cocoa-touch 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.

最佳答案

假设有两个日期:

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/

相关文章:

iphone - 将数据重新加载到 NSArray 时出现问题(可能是因为 ARC)

ios - UILabel 中的 NSAttributedString 是否会忽略标签的 numberOfLines 属性?

objective-c - 从 NSString 中删除开始和尾随的新行字符

iphone - 如何检查 NSSet 或 NSCountedSet 中是否存在现有项目?

iphone - 在 iPhone 应用程序中使用 libxml2 解析 xml 文件的教程或示例代码

iphone - 移动 x 偏移时的 CGContextDrawImage

objective-c - 函数 'UI_USER_INTERFACE_IDIOM' 的隐式声明在 C99 中无效

ios - 调整 UITableView 背景 View 的框架?

iphone - 监测接近度时是否可以不关闭显示?

iphone - sqlite3 更新在 ios 中不起作用