Ios 两个日期之间的时间间隔返回零

Ios 两个日期之间的时间间隔返回零,ios,objective-c,nsdate,nsdatecomponents,Ios,Objective C,Nsdate,Nsdatecomponents,我正在计算两个NSDate之间的时间差,它始终返回0.0000。我使用相同的逻辑计算时间戳,并且格式正确。。当我尝试单独记录日期时,它会正确打印,当我打印差异时,它会打印0.0000。。。这是计算日期的代码 -(NSDate *) toLocalTime { NSTimeZone *tz = [NSTimeZone defaultTimeZone]; NSInteger seconds = [tz secondsFromGMTForDate: [NSDate date]]; return [NS

我正在计算两个NSDate之间的时间差,它始终返回0.0000。我使用相同的逻辑计算时间戳,并且格式正确。。当我尝试单独记录日期时,它会正确打印,当我打印差异时,它会打印0.0000。。。这是计算日期的代码

-(NSDate *) toLocalTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: [NSDate date]];
return [NSDate dateWithTimeInterval: seconds sinceDate: [NSDate date]];
}
这是我发现差异的代码

NSLog(@"the time when the location was updated is %@",timeWhenTheLocationWasUpdated);
NSLog(@"the time when the server was contacted last time was %@",timeWhenLastLocationPosted);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss ZZZ"];
NSDate *timeofUpdatingLocation = [[NSDate alloc] init];
NSDate *timeofPostingToTheServer = [[NSDate alloc]init];
timeofUpdatingLocation = [dateFormatter dateFromString:timeWhenTheLocationWasUpdated];
timeofPostingToTheServer = [dateFormatter dateFromString:timeWhenLastLocationPosted];
NSTimeInterval difference = [timeofPostingToTheServer timeIntervalSinceDate:timeofUpdatingLocation];
NSLog(@"the difference between posting the location to the server and updating the location is %f",difference);

代码开头的NSlog都以日期格式化程序中提到的格式正确打印日期。

在Objective-C中,向零对象发送消息是完全合法的。您返回0/零/假

NSdateFormatter
如果字符串与格式不匹配,则调用
dateFromString
对象将返回nil

我猜您对
dateFromString
的调用失败,并且
timeofPostingToTheServer
为nil,所以返回0


(作为一个脚注,正如rmaddy在他的评论中所建议的,toLocalTime似乎对您试图解决的问题没有意义)

用实际的日志输出更新您的问题。您还需要记录
timeofupdateingglocation
timeofpostingtheserver
(我猜两者都是
nil
)。那么
toLocalTime
方法与问题有何关系?我猜您的
dateFromString
在这两个日期都失败,从而使两个日期相同,因此它们之间的时间间隔为0。