How to parse string value like 12:02:21.3213
to NSTimeInterval
? NSDateComponentsFormatter
, available since iOS8, supports only formatting, not parsing.
如何将字符串值解析为12:02:21.3213到NSTimeInterval?自iOS8起可用的NSDateComponentsFormatter仅支持格式化,而不支持解析。
2 个解决方案
#1
6
Here is how you can do it in Swift:
以下是在Swift中如何做到这一点:
func parseDuration(timeString:String) -> NSTimeInterval {
guard !timeString.isEmpty else {
return 0
}
var interval:Double = 0
let parts = timeString.componentsSeparatedByString(":")
for (index, part) in parts.reverse().enumerate() {
interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
}
return interval
}
It works for values like 2:12:12
, 02:01:23.123213
它适用于像2:12:12,02:01:23.123213这样的值
#2
6
The solution provided by Bartosz Hernas worked for me, thank you!
Bartosz Hernas提供的解决方案为我工作,谢谢!
For convenience, here it is for Swift 3:
为方便起见,这里是Swift 3:
func parseDuration(_ timeString:String) -> TimeInterval {
guard !timeString.isEmpty else {
return 0
}
var interval:Double = 0
let parts = timeString.components(separatedBy: ":")
for (index, part) in parts.reversed().enumerated() {
interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
}
return interval
}
#1
6
Here is how you can do it in Swift:
以下是在Swift中如何做到这一点:
func parseDuration(timeString:String) -> NSTimeInterval {
guard !timeString.isEmpty else {
return 0
}
var interval:Double = 0
let parts = timeString.componentsSeparatedByString(":")
for (index, part) in parts.reverse().enumerate() {
interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
}
return interval
}
It works for values like 2:12:12
, 02:01:23.123213
它适用于像2:12:12,02:01:23.123213这样的值
#2
6
The solution provided by Bartosz Hernas worked for me, thank you!
Bartosz Hernas提供的解决方案为我工作,谢谢!
For convenience, here it is for Swift 3:
为方便起见,这里是Swift 3:
func parseDuration(_ timeString:String) -> TimeInterval {
guard !timeString.isEmpty else {
return 0
}
var interval:Double = 0
let parts = timeString.components(separatedBy: ":")
for (index, part) in parts.reversed().enumerated() {
interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
}
return interval
}