I'm new swift developer i don't know how to convert duration from youtube api to normal time format?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With