Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert duration form youtube api in swift?

Tags:

xcode

ios

swift

I'm new swift developer i don't know how to convert duration from youtube api to normal time format?

like image 304
sony Avatar asked May 05 '16 10:05

sony


1 Answers

A simpler implementation considering return value in hh:mm:ss format only.

extension String {

    func getYoutubeFormattedDuration() -> String {

        let formattedDuration = self.stringByReplacingOccurrencesOfString("PT", withString: "").stringByReplacingOccurrencesOfString("H", withString: ":").stringByReplacingOccurrencesOfString("M", withString: ":").stringByReplacingOccurrencesOfString("S", withString: "")

        let components = formattedDuration.componentsSeparatedByString(":")
        var duration = ""
        for component in components {
            duration = duration.characters.count > 0 ? duration + ":" : duration
            if component.characters.count < 2 {
                duration += "0" + component
                continue
            }
            duration += component
        }

        return duration

    }

}

**Swift 3

  func getYoutubeFormattedDuration() -> String {

    let formattedDuration = self.replacingOccurrences(of: "PT", with: "").replacingOccurrences(of: "H", with:":").replacingOccurrences(of: "M", with: ":").replacingOccurrences(of: "S", with: "")

    let components = formattedDuration.components(separatedBy: ":")
    var duration = ""
    for component in components {
        duration = duration.characters.count > 0 ? duration + ":" : duration
        if component.characters.count < 2 {
            duration += "0" + component
            continue
        }
        duration += component
    }

    return duration

}

Sample Results:

"PT3H2M31S".getYoutubeFormattedDuration() //returns "03:02:31"
"PT2M31S".getYoutubeFormattedDuration() //returns "02:31"
"PT31S".getYoutubeFormattedDuration() //returns "31"
like image 109
mohonish Avatar answered Sep 21 '22 08:09

mohonish