我有NSDate比较问题。我尝试了几个解决方案,但是在搜索问题时发现了一些问题,但没有任何变化:我比较两个日期,并且总是得到NSOrderedSame或NSTimeIntervals = 0.0000;NSDate比较总是返回NSOrderedSame
我的代码如下所示:
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
你可以发布你如何初始化'NSDateFormatter'?我相信问题应该在那里。 – atxe
最有可能的一个或两个你的NSDate对象是零。请注意,您不记录'serverDate'。 –
我已经为你添加了dateformatter。 @Hot Licks:服务器日期在NSLog中,查看底部调试屏幕中服务器的日期与当地日期的不同。 – Wenduros