2014-05-23 154 views
0

我需要一個NSString顯示使用2 NSStrings如何計算總的行駛時間

NSString *origin = [NSString stringWithFormat:@"5:30"]; 
NSString *destiny = [NSString stringWithFormat:@"6:00"]; 

問題是我不知道如何來共行駛時間格式化這個NSStringsNSDatedestiny - origin因此輸出將是一個新的NSString,說30 minutes

編輯:我剛剛查了一點關於NSDateFormatter但如果我使用它:

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"HH:mm"]; 
NSDate * mydate = [dateFormatter dateFromString:origin]; 

NSDate返回我nil有什麼錯嗎?

任何幫助將不勝感激。

+1

你調查'NSDateFormatter'?這將是答案,因爲它會在日期和字符串之間轉換(在兩個方向上)。但是如果你看了看,看不出有什麼理由,那麼或許還有一個更具體的問題,我們可以回答? – Tommy

+0

你需要的是'NSDateFormatter',文檔在這裏:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html – Jack

+1

'NSDateFormatter'不是正確的解決方案,如果你只有兩次。這兩個時間串是從哪裏來的?你爲什麼用字符串跟蹤時間? – rmaddy

回答

0
NSString *origin = @"5:30"; 
NSString *destiny = @"6:00"; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"H:mm"]; 

NSDate *originDate = [dateFormatter dateFromString:origin]; 
NSDate *destinyDate = [dateFormatter dateFromString:destiny]; 

NSTimeInterval interval = [destinyDate timeIntervalSinceDate:originDate]; 
NSDate *intervalDate = [NSDate dateWithTimeInterval:interval sinceDate:originDate ]; 

NSDateComponents *comps =[[NSCalendar currentCalendar] components:NSMinuteCalendarUnit 
                 fromDate:originDate 
                  toDate:intervalDate 
                  options:0]; 

現在NSDateComponents將持有分鐘的差別

NSLog(@"%ld", [comps minute]); 

將記錄30

如果你想的小時和分鐘,你可以做

NSString *origin = @"5:30"; 
NSString *destiny = @"7:00"; 

// .... 

NSDateComponents *comps =[[NSCalendar currentCalendar] components: (NSMinuteCalendarUnit|NSHourCalendarUnit) 
                 fromDate:originDate 
                  toDate:intervalDate 
                  options:0]; 

現在比賽將持續90分鐘,時間爲1小時30分鐘。

NSLog(@"%ld %ld", [comps hour],[comps minute]); 

日誌1 30

0
NSString *origin = @"5:30"; 
NSString *destiny = @"6:00"; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"H:mm"]; 
NSDate *originDate = [dateFormatter dateFromString:origin]; 
NSDate *destinyDate = [dateFormatter dateFromString:destiny]; 

NSTimeInterval diffInSeconds = [destinyDate timeIntervalSinceDate:originDate]; 
NSTimeInterval diffInMinutes = diffInSeconds/60; 
NSString *minutesString = [NSString stringWithFormat:@"%0.0f", diffInMinutes]; 
+0

使用HH:mm的代碼返回nil,因爲HH預計兩位數小時,並且您的日期只包含一位數字。 – Rob