2016-07-15 119 views
-2

我正在計算兩個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以日期格式化程序中提及的格式正確輸入日期。

+0

用實際的日誌輸出更新你的問題。你還需要記錄'timeofUpdatingLocation'和'timeofPostingToTheServer'(我猜這兩個都是'nil')。 – rmaddy

+0

'toLocalTime'方法與這個問題有什麼關係? – rmaddy

+0

我的猜測是你的'dateFromString'這兩個日期都失敗了,從而使兩個日期完全相同,因此它們之間的時間爲0。 – Putz1103

回答

2

在Objective-C中,將消息發送給nil對象是完全合法的。你得到0/nil/FALSE。

NSdateFormatter如果字符串與格式不匹配,則對象將返回nil,從dateFromString調用。

我的猜測是,你要dateFromString調用失敗和timeofPostingToTheServer是零,所以你要回0

(而作爲一個註腳,如rmaddy在他的意見建議,toLocalTime似乎不對你想解決的問題有意義)