2011-06-22 76 views
1

您好我有代碼分離小時,分,秒 現在我要它轉換爲seconds.and的NSNumber轉換HH:MM:SS以秒在Xcode

NSRange range = [string rangeOfString:@":"]; 
    NSString *hour = [string substringToIndex:range.location]; 
    NSLog(@"time %@",hour); 

    NSRange range1= NSMakeRange(2,2); 
    NSString *min = [string substringWithRange:range1]; 
    NSLog(@"time %@",min); 
    NSRange range2 = NSMakeRange(5,2); 
    NSString *sec = [string substringWithRange:range2]; 
    NSLog(@"time %@",sec); 
+1

你想,因爲日曆(1970年)開始秒或自午夜? – Manuel

回答

0

要從已經什麼,

double totalSeconds = [hour doubleValue] * 60 * 60 + [min doubleValue] * 60 + [sec doubleValue]; 
NSNumber * seconds = [NSNumber numberWithDouble:totalSeconds]; 
12

如果你想找出多少秒的小時,分​​鍾和秒的總,你可以做這樣的事情:

- (NSNumber *)secondsForTimeString:(NSString *)string { 

    NSArray *components = [string componentsSeparatedByString:@":"]; 

    NSInteger hours = [[components objectAtIndex:0] integerValue]; 
    NSInteger minutes = [[components objectAtIndex:1] integerValue]; 
    NSInteger seconds = [[components objectAtIndex:2] integerValue]; 

    return [NSNumber numberWithInteger:(hours * 60 * 60) + (minutes * 60) + seconds]; 
} 
+0

謝謝,我明白了 – Sheik

0

以下是用於將時間字符串(HH:MM:SS)的字符串擴展到秒

extension String { 
    func secondsFromString (string: String) -> Int { 
     var components: Array = string.componentsSeparatedByString(":") 
     var hours = components[0].toInt()! 
     var minutes = components[1].toInt()! 
     var seconds = components[2].toInt()! 
     return Int((hours * 60 * 60) + (minutes * 60) + seconds) 
    } 
} 

如何使用

var exampleString = String().secondsFromString("00:30:00") 
0

可以使用(Swift 3):

extension String { 
    func numberOfSeconds() -> Int { 
     var components: Array = self.components(separatedBy: ":") 
     let hours = Int(components[0]) ?? 0 
     let minutes = Int(components[1]) ?? 0 
     let seconds = Int(components[2]) ?? 0 
     return (hours * 3600) + (minutes * 60) + seconds 
    } 
} 

再舉例來說,使用它像:

let seconds = "01:30:10".numberOfSeconds() 
print("%@ seconds", seconds) 

,它將打印:

3790 seconds 
相關問題