两个日期之间的时间间隔 returns 无
Time Interval between two dates returns nil
我正在计算两个 NSDate 之间的时间差,它总是 returns 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 中,向 nil 对象发送消息是完全合法的。你回来 0/nil/FALSE.
如果字符串与格式不匹配,NSdateFormatter
对象 return 零来自对 dateFromString
的调用。
我的猜测是您对 dateFromString
的调用失败并且 timeofPostingToTheServer
为零,因此您返回 0。
(作为脚注,正如 rmaddy 在他的评论中所建议的那样,toLocalTime 似乎对您要解决的问题没有意义)
我正在计算两个 NSDate 之间的时间差,它总是 returns 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 中,向 nil 对象发送消息是完全合法的。你回来 0/nil/FALSE.
如果字符串与格式不匹配,NSdateFormatter
对象 return 零来自对 dateFromString
的调用。
我的猜测是您对 dateFromString
的调用失败并且 timeofPostingToTheServer
为零,因此您返回 0。
(作为脚注,正如 rmaddy 在他的评论中所建议的那样,toLocalTime 似乎对您要解决的问题没有意义)