如何比较两个 NSDates:哪个是最近的? [英] How to compare two NSDates: Which is more recent?

查看:26
本文介绍了如何比较两个 NSDates:哪个是最近的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to achieve a dropBox sync and need to compare the dates of two files. One is on my dropBox account and one is on my iPhone.

我想出了以下方法,但得到了意想不到的结果.我想我在比较两个日期时做错了一些事情.我只是使用了 > <运算符,但我想这不好,因为我正在比较两个 NSDate 字符串.我们开始:

I came up with the following, but I get unexpected results. I guess I'm doing something fundamentally wrong when comparing the two dates. I simply used the > < operators, but I guess this is no good as I am comparing two NSDate strings. Here we go:

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.");
}

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

This gave me the following (random & wrong) output:

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.

或者这个恰好是正确的:

or this one which happens to be correct:

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;

然后下面的比较会告诉哪个是早/晚/相同:

Then the following comparison will tell which is earlier/later/same:

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 类文档了解更多详情.

这篇关于如何比较两个 NSDates:哪个是最近的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆