Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse string to NSTimeInterval

Tags:

ios

swift

How to parse string value like 12:02:21.3213 to NSTimeInterval? NSDateComponentsFormatter, available since iOS8, supports only formatting, not parsing.

like image 885
Bartosz Hernas Avatar asked Feb 15 '16 10:02

Bartosz Hernas


2 Answers

Here is how you can do it in Swift,

It works for values like 2:12:12, 02:01:23.123213

Swift 5 (by @Youstanzr):

extension String {
    func convertToTimeInterval() -> TimeInterval {
        guard self != "" else {
            return 0
        }

        var interval:Double = 0

        let parts = self.components(separatedBy: ":")
        for (index, part) in parts.reversed().enumerated() {
            interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
        }

        return interval
    }
}

Swift 3 (by @Torre Lasley)

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
}

Swift 2

    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
    }
like image 104
Bartosz Hernas Avatar answered Oct 13 '22 08:10

Bartosz Hernas


Here is the Swift 5 version that I've made of @Bartosz answer

extension String {
    func convertToTimeInterval() -> TimeInterval {
        guard self != "" else {
            return 0
        }

        var interval:Double = 0

        let parts = self.components(separatedBy: ":")
        for (index, part) in parts.reversed().enumerated() {
            interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
        }

        return interval
    }
}
like image 20
Youstanzr Avatar answered Oct 13 '22 07:10

Youstanzr