nsdate比较总是返回nsorderedsame



我有NSDATE比较的问题。我尝试了在谷歌搜索问题时发现的几种解决方案,但没有任何更改:我比较两个日期,并且我总是会得到nsorderedsame或nstimeintervals = 0.0000之间的差异;

我的代码看起来像这样:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    for (checklisteModel *updateRecord in updateArray) 
    {
        NSDate *serverDate = [inputFormatter dateFromString:updateRecord.last_update];
        NSString *lastUpdateFromLocalRecord = [self getLastUpdateForChecklisteItemWithID:updateRecord.checklisteID];
        NSDate *localDate = [inputFormatter dateFromString:lastUpdateFromLocalRecord];
        NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
        NSLog(@"checkliste ID: %i",updateRecord.checklisteID);
        NSLog(@"server Date: ----- %@",[fmt stringFromDate:serverDate]);
        NSLog(@"local Date: ----- %@",lastUpdateFromLocalRecord);

        NSLog(@"difference of dates: %f",[serverDate timeIntervalSinceDate:localDate]);

        NSTimeInterval distanceBetweenDates = [serverDate timeIntervalSinceDate:localDate];
        double secondsInMinute = 60;
        NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
        if (secondsBetweenDates == 0)
            NSLog(@"seconds between == 0");
        else if (secondsBetweenDates < 0)
            NSLog(@"seconds between < 0");
        else
            NSLog(@"seconds between > 0");

        //last_update on server is earlier than local
        if ([serverDate compare:localDate] == NSOrderedAscending) 
        {
            NSLog(@"Server data is earlier than local data");
            NSLog([NSString stringWithFormat:@"server data: %@, local data: %@",updateRecord.last_update,lastUpdateFromLocalRecord]);
        }
        // server data is later than local data
        else if ([serverDate compare:localDate] == NSOrderedDescending) 
        {
            NSLog(@"Server data is later than local data");
            NSLog([NSString stringWithFormat:@"server data: %@, local data: %@",updateRecord.last_update,lastUpdateFromLocalRecord]);
        }
        else 
        {
            NSLog(@"Server data and local data are the same");
        }
    }

我的调试的一部分显示了以下内容:

checkliste ID: 21
server Date: ----- 
local Date: ----- 2012-10-29 10:13:46
difference of dates: 3810.000000
seconds between > 0
Server data is later than local data
server data: 2012-10-29 11:17:16, local data: 2012-10-29 10:13:46
NSLog(@"server Date: ----- %@",updateRecord.last_update);

您不是在这里记录serverDate,因此正如热舔建议的那样,它很有可能是零。您可以将消息发送到Objective-C中的nil,结果是0nil。您认为NSorderedSame的价值是什么?我敢打一美元,它是0

[inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

我注意到您的日期格式化格式的输入格式与您的记录完全不匹配,因此也许预期输入与提供的内容之间的区别足以防止格式化者创建日期。尝试将秒添加到inputFormatter的日期格式。

相关内容

  • 没有找到相关文章

最新更新