Bartosz Hernas Bartosz Hernas - 1 month ago 16
iOS Question

How to parse string to NSTimeInterval

How to parse string value like

12:02:21.3213
to
NSTimeInterval
?
NSDateComponentsFormatter
, available since iOS8, supports only formatting, not parsing.

Answer

Here is how you can do it in 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

Comments