我正在计算两个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都以日期格式化程序中提到的格式正确打印日期。
答案 0 :(得分:2)
在Objective-C中,向nil对象发送消息是完全合法的。你回来0 /零/假。
如果字符串与格式不匹配,则 $one = $two = 0; // empty variables
foreach($Seq as $key => $value) {
foreach ($value as $val) {
if ($val == 1) {
$one++;
}else {
$two++;
}
}
}
echo "total number of one's ". $one ."<br>";
echo "total number of two's ". $two ."<br>";
个对象从NSdateFormatter
的调用返回nil。
我的猜测是,您对dateFromString
的调用失败且dateFromString
为零,因此您将返回0。
(作为一个脚注,正如rmaddy在他的评论中所暗示的那样,对于你正试图解决的问题,本地时间似乎没有意义)