How to Convert duration form youtube api in swift? - ios

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"

Using String Extension:
extension String{
func formatDurationsFromYoutubeAPItoNormalTime (targetString : String) ->String{
var timeDuration : NSString!
let string: NSString = targetString
if string.rangeOfString("H").location == NSNotFound && string.rangeOfString("M").location == NSNotFound{
if string.rangeOfString("S").location == NSNotFound {
timeDuration = NSString(format: "00:00")
} else {
var secs: NSString = targetString
secs = secs.substringFromIndex(secs.rangeOfString("PT").location + "PT".characters.count)
secs = secs.substringToIndex(secs.rangeOfString("S").location)
timeDuration = NSString(format: "00:%02d", secs.integerValue)
}
}
else if string.rangeOfString("H").location == NSNotFound {
var mins: NSString = targetString
mins = mins.substringFromIndex(mins.rangeOfString("PT").location + "PT".characters.count)
mins = mins.substringToIndex(mins.rangeOfString("M").location)
if string.rangeOfString("S").location == NSNotFound {
timeDuration = NSString(format: "%02d:00", mins.integerValue)
} else {
var secs: NSString = targetString
secs = secs.substringFromIndex(secs.rangeOfString("M").location + "M".characters.count)
secs = secs.substringToIndex(secs.rangeOfString("S").location)
timeDuration = NSString(format: "%02d:%02d", mins.integerValue, secs.integerValue)
}
} else {
var hours: NSString = targetString
hours = hours.substringFromIndex(hours.rangeOfString("PT").location + "PT".characters.count)
hours = hours.substringToIndex(hours.rangeOfString("H").location)
if string.rangeOfString("M").location == NSNotFound && string.rangeOfString("S").location == NSNotFound {
timeDuration = NSString(format: "%02d:00:00", hours.integerValue)
} else if string.rangeOfString("M").location == NSNotFound {
var secs: NSString = targetString
secs = secs.substringFromIndex(secs.rangeOfString("H").location + "H".characters.count)
secs = secs.substringToIndex(secs.rangeOfString("S").location)
timeDuration = NSString(format: "%02d:00:%02d", hours.integerValue, secs.integerValue)
} else if string.rangeOfString("S").location == NSNotFound {
var mins: NSString = targetString
mins = mins.substringFromIndex(mins.rangeOfString("H").location + "H".characters.count)
mins = mins.substringToIndex(mins.rangeOfString("M").location)
timeDuration = NSString(format: "%02d:%02d:00", hours.integerValue, mins.integerValue)
} else {
var secs: NSString = targetString
secs = secs.substringFromIndex(secs.rangeOfString("M").location + "M".characters.count)
secs = secs.substringToIndex(secs.rangeOfString("S").location)
var mins: NSString = targetString
mins = mins.substringFromIndex(mins.rangeOfString("H").location + "H".characters.count)
mins = mins.substringToIndex(mins.rangeOfString("M").location)
timeDuration = NSString(format: "%02d:%02d:%02d", hours.integerValue, mins.integerValue, secs.integerValue)
}
}
return timeDuration as String
}
}
Usage:
override func viewWillAppear(animated: Bool) {
let youtubeVideoDurationString = "PT15M51S"
let resultString = youtubeVideoDurationString.formatDurationsFromYoutubeAPItoNormalTime(youtubeVideoDurationString)
print(resultString)
}

To Convert Hour:Minute:Second format :-
Using String Extension:
extension String{
func parseVideoDurationOfYoutubeAPI(videoDuration: String?) -> String {
var videoDurationString = videoDuration! as NSString
var hours: Int = 0
var minutes: Int = 0
var seconds: Int = 0
let timeRange = videoDurationString.rangeOfString("T")
videoDurationString = videoDurationString.substringFromIndex(timeRange.location)
while videoDurationString.length > 1 {
videoDurationString = videoDurationString.substringFromIndex(1)
let scanner = NSScanner(string: videoDurationString as String) as NSScanner
var part: NSString?
scanner.scanCharactersFromSet(NSCharacterSet.decimalDigitCharacterSet(), intoString: &part)
let partRange: NSRange = videoDurationString.rangeOfString(part! as String)
videoDurationString = videoDurationString.substringFromIndex(partRange.location + partRange.length)
let timeUnit: String = videoDurationString.substringToIndex(1)
if (timeUnit == "H") {
hours = Int(part as! String)!
}
else if (timeUnit == "M") {
minutes = Int(part as! String)!
}
else if (timeUnit == "S") {
seconds = Int(part! as String)!
}
else{
}
}
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}
}
Usage:
override func viewWillAppear(animated: Bool) {
let youtubeVideoDurationString = "PT15M51S"
let result_Hour_Minute_Second = youtubeVideoDurationString.parseVideoDurationOfYoutubeAPI("PT15M51S") as String
print("result_Hour_Minute_Second: \(result_Hour_Minute_Second)")
}

In Swift 5
extension String {
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.count > 0 ? duration + ":" : duration
if component.count < 2 {
duration += "0" + component
continue
}
duration += component
}
return duration
}
}
Usage:
let youtubeVideoDurationString = "PT2M24S"
youtubeVideoDurationString.getYoutubeFormattedDuration() //returns 02:24

Related

Convert String minutes seconds to Int

I've a string with minutes and seconds in format "minutes:seconds". For example, "5:36". I want to convert it to Int value. For example "5:36" string should be 336 Int value. How this can be done?
let timeString = "5:36"
let timeStringArray = timeString.split(separator: ":")
let minutesInt = Int(timeStringArray[0]) ?? 0
let secondsInt = Int(timeStringArray[1]) ?? 0
let resultInt = minutesInt * 60 + secondsInt
print(resultInt)
Here's a simple extension you can use which will validate the format of your input string too:
import Foundation
extension String {
func toSeconds() -> Int? {
let elements = components(separatedBy: ":")
guard elements.count == 2 else {
print("Provided string doesn't have two sides separated by a ':'")
return nil
}
guard let minutes = Int(elements[0]),
let seconds = Int(elements[1]) else {
print("Either the minute value or the seconds value cannot be converted to an Int")
return nil
}
return (minutes*60) + seconds
}
}
Usage:
let testString1 = "5:36"
let testString2 = "35:36"
print(testString1.toSeconds()) // prints: "Optional(336)"
print(testString2.toSeconds()) // prints: "Optional(2136)"
I tried out your example on the playground here's the code:
import Foundation
let time1String = "0:00"
let time2String = "5:36"
let timeformatter = DateFormatter()
timeformatter.dateFormat = "m:ss"
let time1 = timeformatter.date(from: time1String)
let time2 = timeformatter.date(from: time2String)
if let time1 = time1 {
print(time2?.timeIntervalSince(time1)) // prints: Optional(336.0)
}

I am trying to get an icon array to display in my weather app, but can not seem to get UIImage to display them

This is my code so far, with no errors, but it is not picking the dates from the 5 day forecast. What is wrong in this code?
//: to display the 5 day date array from the open weather API
enter code herevar temperatureArray: Array = Array()
var dayNumber = 0
var readingNumber = 0
if let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
if let mainArray = jsonObj!.value(forKey: "list") as? NSArray {
for dict in mainArray {
if let mainDictionary = (dict as! NSDictionary).value(forKey: "main") as? NSDictionary {
if let temperature = mainDictionary.value(forKey: "temp_max") as? Double {
if readingNumber == 0 {
temperatureArray.append(temperature)
} else if temperature > temperatureArray[dayNumber] {
temperatureArray[dayNumber] = temperature
}
} else {
print("Error: unable to find temperature in dictionary")
}
} else {
print("Error: unable to find main dictionary")
}
readingNumber += 1
if readingNumber == 8 {
readingNumber = 0
dayNumber += 1
}
var dateArray: Array<String> = Array()
var dayNumber = 0
var readingNumber = 0
if let weatherArray = jsonObj!.value(forKey: "list") as? NSArray {
for dict in weatherArray {
if let weatherDictionary = (dict as! NSDictionary).value(forKey: "list") as? NSDictionary {
if let date = weatherDictionary.value(forKey: "dt_txt") as? String {
if readingNumber == 0 {
dateArray.append(date)
} else if date > dateArray[dayNumber] {
dateArray[dayNumber] = date
}
}
} else {
print("Error: unable to find date in dictionary")
}
readingNumber += 1
if readingNumber == 8 {
readingNumber = 0
dayNumber += 1
}
}
}
}
}
}
func fixTempForDisplay(temp: Double) -> String {
let temperature = round(temp)
let temperatureString = String(format: "%.0f", temperature)
return temperatureString
}
DispatchQueue.main.async {
self.weatherLabel1.text = "Today: (fixTempForDisplay(temp: temperatureArray[0]))°C"
self.weatherLabel2.text = "Tomorrow: (fixTempForDisplay(temp: temperatureArray[1]))°C"
self.weatherLabel3.text = "Day 3: (fixTempForDisplay(temp: temperatureArray[2]))°C"
self.weatherLabel4.text = "Day 4: (fixTempForDisplay(temp: temperatureArray[3]))°C"
self.weatherLabel5.text = "Day 5: (fixTempForDisplay(temp: temperatureArray[4]))°C"
func formatDate(date: NSDate) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
return dateFormatter.string(from: date as Date)
}
self.dateLabel1.text = ": \(formatDate(date: dateArray[0]))"
self.dateLabel2.text = ": \(formatDate(date: dateArray[1]))"
self.dateLabel3.text = ": \(formatDate(date: dateArray[2]))"
self.dateLabel4.text = ": \(formatDate(date: dateArray[3]))"
self.dateLabel5.text = ": \(formatDate(date: dateArray[4]))"
}
}
}
dataTask.resume()
}
}
It looks to me like you need to change your icon array to contain strings
var iconArray: Array<String> = Array()
and then when parsing the json text
if let icon = weatherDictionary.value(forKey: "icon") as? String {
and finally
self.iconImage1.image = UIImage(named: iconArray[0])
self.iconImage2.image = UIImage(named: iconArray[1])
Of course the below comparison won't work anymore when icon is a string but I don't understand any of this if/else clasue so I don't know what to replace it with
if readingNumber == 0 {
iconArray.append(icon)
} else if icon > iconArray[dayNumber] { //This won't work now.
iconArray[dayNumber] = icon
}

How to parse a ISO 8601 duration format in Swift?

I have a function below which I use to format a string. The string is something like this "PT1H3M20S" which means 1 hour 3 minutes and 20 seconds. In my function, I want to format the string to 1:03:20 and it works fine but sometimes, I get the string like this "PT1H20S" which means 1 hour and 20 seconds and my function format it like this 1:20 which makes people read it as 1 minute and 20 seconds. Any suggestions?
func formatDuration(videoDuration: String) -> String{
let formattedDuration = videoDuration.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.count > 0 ? duration + ":" : duration
if component.count < 2 {
duration += "0" + component
continue
}
duration += component
}
// instead of 01:10:10, display 1:10:10
if duration.first == "0"{
duration.remove(at: duration.startIndex)
}
return duration
}
Call it:
print(formatDuration(videoDuration: "PT1H15S")
You can also just search the indexes of your hours, minutes and seconds and use DateComponentsFormatter positional style to format your video duration:
Create a static positional date components formatter:
extension Formatter {
static let positional: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
return formatter
}()
}
And your format duration method:
func formatVideo(duration: String) -> String {
var duration = duration
if duration.hasPrefix("PT") { duration.removeFirst(2) }
let hour, minute, second: Double
if let index = duration.firstIndex(of: "H") {
hour = Double(duration[..<index]) ?? 0
duration.removeSubrange(...index)
} else { hour = 0 }
if let index = duration.firstIndex(of: "M") {
minute = Double(duration[..<index]) ?? 0
duration.removeSubrange(...index)
} else { minute = 0 }
if let index = duration.firstIndex(of: "S") {
second = Double(duration[..<index]) ?? 0
} else { second = 0 }
return Formatter.positional.string(from: hour * 3600 + minute * 60 + second) ?? "0:00"
}
let duration = "PT1H3M20S"
formatVideo(duration: duration) // "1:03:20"
Since you need to see what unit is after each number, you can't start by removing the units from the string.
Here is a solution that uses Scanner to parse the original string and finds the number of hours, minutes, and seconds to build the final result.
This also changes the return value to be optional to indicate that the passed in string isn't valid.
func formatDuration(videoDuration: String) -> String? {
let scanner = Scanner(string: videoDuration)
if scanner.scanString("PT", into: nil) {
var hours = 0
var mins = 0
var secs = 0
let units = CharacterSet(charactersIn: "HMS")
while !scanner.isAtEnd {
var num = 0
if scanner.scanInt(&num) {
var unit: NSString?
if scanner.scanCharacters(from: units, into: &unit) {
switch unit! {
case "H":
hours = num
case "M":
mins = num
case "S":
secs = num
default:
return nil // Invalid unit
}
} else {
return nil // No unit after the number
}
} else {
return nil // No integer
}
}
if hours > 0 {
return String(format: "%d:%02d:%02d", hours, mins, secs)
} else {
return String(format: "%02d:%02d", mins, secs)
}
} else {
return nil // No leading PT
}
}
print(formatDuration(videoDuration: "PT1H3M20S") ?? "bad")
print(formatDuration(videoDuration: "PT1H15S") ?? "bad")
print(formatDuration(videoDuration: "PT4M6") ?? "bad")
Output:
1:03:20
1:00:15
bad
In your case, your string carries no character for minutes, so you can make a check if the string does not contain minutes, then add "00:" between 1:20 and format appropriately.

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.
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
}
The solution provided by Bartosz Hernas worked for me, thank you!
For convenience, here it is for 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
}
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
}
}

How to format the duration returned from youtube api v3 reuqest using objective-c?

how to format this time period "PT1H20M10S" to be "1:20:10" using objective-c ?
this is returned from a request to youtube . it gives me a time period. how to style "PT1H20M10S" to be appeared like this "1:20:10" to be human readable in my application ?
You can use the following code:
- (NSString *)parseDuration:(NSString *)duration {
NSInteger hours = 0;
NSInteger minutes = 0;
NSInteger seconds = 0;
NSRange timeRange = [duration rangeOfString:#"T"];
duration = [duration substringFromIndex:timeRange.location];
while (duration.length > 1) {
duration = [duration substringFromIndex:1];
NSScanner *scanner = [NSScanner.alloc initWithString:duration];
NSString *part = [NSString.alloc init];
[scanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&part];
NSRange partRange = [duration rangeOfString:part];
duration = [duration substringFromIndex:partRange.location + partRange.length];
NSString *timeUnit = [duration substringToIndex:1];
if ([timeUnit isEqualToString:#"H"])
hours = [part integerValue];
else if ([timeUnit isEqualToString:#"M"])
minutes = [part integerValue];
else if ([timeUnit isEqualToString:#"S"])
seconds = [part integerValue];
}
return [NSString stringWithFormat:#"%02d:%02d:%02d", hours, minutes, seconds];
}
You can also read up on ISO_8601 durations here.
Using String Extension:
extension String{
func parseVideoDurationOfYoutubeAPI(videoDuration: String?) -> String {
var videoDurationString = videoDuration! as NSString
var hours: Int = 0
var minutes: Int = 0
var seconds: Int = 0
let timeRange = videoDurationString.rangeOfString("T")
videoDurationString = videoDurationString.substringFromIndex(timeRange.location)
while videoDurationString.length > 1 {
videoDurationString = videoDurationString.substringFromIndex(1)
let scanner = NSScanner(string: videoDurationString as String) as NSScanner
var part: NSString?
scanner.scanCharactersFromSet(NSCharacterSet.decimalDigitCharacterSet(), intoString: &part)
let partRange: NSRange = videoDurationString.rangeOfString(part! as String)
videoDurationString = videoDurationString.substringFromIndex(partRange.location + partRange.length)
let timeUnit: String = videoDurationString.substringToIndex(1)
if (timeUnit == "H") {
hours = Int(part as! String)!
}
else if (timeUnit == "M") {
minutes = Int(part as! String)!
}
else if (timeUnit == "S") {
seconds = Int(part! as String)!
}
else{
}
}
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}
}
Usage:
override func viewWillAppear(animated: Bool) {
let youtubeVideoDurationString = "PT15M51S"
let result_Hour_Minute_Second = youtubeVideoDurationString.parseVideoDurationOfYoutubeAPI("PT15M51S") as String
print("result_Hour_Minute_Second: \(result_Hour_Minute_Second)")
}
you can use scanner to extract the numbers as
NSString *answerString;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
[scanner scanCharactersFromSet:numbers intoString:&numberString];
int number = [answerString integerValue];
try this code.. i got my output correct using this code..
func formatDurations (sender : String) ->String{
var timeDuration : NSString!
let string: NSString = sender
if string.rangeOfString("H").location == NSNotFound && string.rangeOfString("M").location == NSNotFound{
if string.rangeOfString("S").location == NSNotFound {
timeDuration = NSString(format: "00:00")
} else {
var secs: NSString = sender
secs = secs.substringFromIndex(secs.rangeOfString("PT").location + "PT".characters.count)
secs = secs.substringToIndex(secs.rangeOfString("S").location)
timeDuration = NSString(format: "00:%02d", secs.integerValue)
}
}
else if string.rangeOfString("H").location == NSNotFound {
var mins: NSString = sender
mins = mins.substringFromIndex(mins.rangeOfString("PT").location + "PT".characters.count)
mins = mins.substringToIndex(mins.rangeOfString("M").location)
if string.rangeOfString("S").location == NSNotFound {
timeDuration = NSString(format: "%02d:00", mins.integerValue)
} else {
var secs: NSString = sender
secs = secs.substringFromIndex(secs.rangeOfString("M").location + "M".characters.count)
secs = secs.substringToIndex(secs.rangeOfString("S").location)
timeDuration = NSString(format: "%02d:%02d", mins.integerValue, secs.integerValue)
}
} else {
var hours: NSString = sender
hours = hours.substringFromIndex(hours.rangeOfString("PT").location + "PT".characters.count)
hours = hours.substringToIndex(hours.rangeOfString("H").location)
if string.rangeOfString("M").location == NSNotFound && string.rangeOfString("S").location == NSNotFound {
timeDuration = NSString(format: "%02d:00:00", hours.integerValue)
} else if string.rangeOfString("M").location == NSNotFound {
var secs: NSString = sender
secs = secs.substringFromIndex(secs.rangeOfString("H").location + "H".characters.count)
secs = secs.substringToIndex(secs.rangeOfString("S").location)
timeDuration = NSString(format: "%02d:00:%02d", hours.integerValue, secs.integerValue)
} else if string.rangeOfString("S").location == NSNotFound {
var mins: NSString = sender
mins = mins.substringFromIndex(mins.rangeOfString("H").location + "H".characters.count)
mins = mins.substringToIndex(mins.rangeOfString("M").location)
timeDuration = NSString(format: "%02d:%02d:00", hours.integerValue, mins.integerValue)
} else {
var secs: NSString = sender
secs = secs.substringFromIndex(secs.rangeOfString("M").location + "M".characters.count)
secs = secs.substringToIndex(secs.rangeOfString("S").location)
var mins: NSString = sender
mins = mins.substringFromIndex(mins.rangeOfString("H").location + "H".characters.count)
mins = mins.substringToIndex(mins.rangeOfString("M").location)
timeDuration = NSString(format: "%02d:%02d:%02d", hours.integerValue, mins.integerValue, secs.integerValue)
}
}
return timeDuration as String
}
If the video is one hour long the format will be PT#H#M#S and if max 24hours it'll be P#DT#H#M#S. check my modified method below:
NSString *formattedDuration = #"";
NSString *durationregX = #"^(P\\d+DT)[A-Z0-9]+$";
NSPredicate *checking = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", durationregX];
BOOL isDayLengthVideo = [checking evaluateWithObject: duration];
long getDayHours = 0;
if(isDayLengthVideo){
NSArray *sliceDuration = [duration componentsSeparatedByString:#"DT"];
NSString *getDay = [sliceDuration[0] stringByReplacingOccurrencesOfString:#"P" withString:#""];
getDayHours = (long)[getDay integerValue] * 24;
formattedDuration = [[[sliceDuration[1] stringByReplacingOccurrencesOfString:#"H" withString:#":"] stringByReplacingOccurrencesOfString:#"M" withString:#":"] stringByReplacingOccurrencesOfString:#"S" withString:#""];
}else{
formattedDuration = [[[[duration stringByReplacingOccurrencesOfString:#"PT" withString:#""] stringByReplacingOccurrencesOfString:#"H" withString:#":"] stringByReplacingOccurrencesOfString:#"M" withString:#":"] stringByReplacingOccurrencesOfString:#"S" withString:#""];
}
NSString *clean_duration = #"";
NSArray *components = [formattedDuration componentsSeparatedByString:#":"];
NSInteger loopchecker = 0;
for (NSString *component in components) {
loopchecker++;
clean_duration = clean_duration.length > 0 ? [NSString stringWithFormat:#"%#:", clean_duration] : clean_duration; // ""
if(component.length < 2){
clean_duration = loopchecker == 1 && isDayLengthVideo ? [NSString stringWithFormat:#"%ld", ([component integerValue] + getDayHours)] : [NSString stringWithFormat:#"%#0%#", clean_duration, component];
return clean_duration;
continue;
}
clean_duration = [NSString stringWithFormat: #"%#%#", clean_duration, component];
}
return clean_duration;
Simple Swift 4.2 Code
func parseDuration(videoDuration: String?) -> String {
var hours: Int = 0
var minutes: Int = 0
var seconds: Int = 0
if let videoDuration = videoDuration {
var lastIndex = videoDuration.startIndex
if let indexT = videoDuration.index(of: "T") {
lastIndex = videoDuration.index(after: indexT)
if let indexH = videoDuration.index(of: "H") {
let hrs = String(videoDuration[lastIndex..<indexT])
hours = Int(hrs) ?? 0
lastIndex = videoDuration.index(after: indexH)
}
if let indexM = videoDuration.index(of: "M") {
let min = String(videoDuration[lastIndex..<indexM])
minutes = Int(min) ?? 0
lastIndex = videoDuration.index(after: indexM)
}
if let indexS = videoDuration.index(of: "S") {
let sec = String(videoDuration[lastIndex..<indexS])
seconds = Int(sec) ?? 0
}
}
}
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}

Resources