两个日期之间的时间间隔返回无
问题描述:
我正在计算两个NSDates之间的时间差,它总是返回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在代码开始处pr以日期格式化程序中提及的格式正确输入日期。
答
在Objective-C中,将消息发送给nil对象是完全合法的。你得到0/nil/FALSE。
NSdateFormatter
如果字符串与格式不匹配,则对象将返回nil,从dateFromString
调用。
我的猜测是,你要dateFromString
调用失败和timeofPostingToTheServer
是零,所以你要回0
(而作为一个注脚,如rmaddy在他的意见建议,toLocalTime似乎不对你想解决的问题有意义)
用实际的日志输出更新你的问题。你还需要记录'timeofUpdatingLocation'和'timeofPostingToTheServer'(我猜这两个都是'nil')。 – rmaddy
'toLocalTime'方法与这个问题有什么关系? – rmaddy
我的猜测是你的'dateFromString'这两个日期都失败了,从而使两个日期完全相同,因此它们之间的时间为0。 – Putz1103