我正在计算两个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 / nil / FALSE。
NSdateFormatter
dateFromString
如果字符串与格式不匹配,则对象从调用返回nil 。
我的猜测是,您对的调用dateFromString
失败并且timeofPostingToTheServer
为零,因此您将返回0。
(并且作为脚注,正如rmaddy在他的评论中所建议的那样,toLocalTime对于您要解决的问题似乎没有意义)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句