2

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 ?

Alaa Agwa
  • 162
  • 1
  • 12
  • 1
    possible duplicate of [Convert string to date in my iPhone app](http://stackoverflow.com/questions/4380381/convert-string-to-date-in-my-iphone-app) – juanjo Jul 13 '15 at 02:00
  • How is that a duplicate @user2027279 ? And Alaa Agwa do you want it to be an actual time as in seconds, or just in a string format? – soulshined Jul 13 '15 at 03:43
  • 1
    I think that two simple searches would give the answer, you only need to search how to parse an NSDate from a NSString and how to format that date, both with an NSDateFormatter – juanjo Jul 13 '15 at 16:52

6 Answers6

5

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.

timominous
  • 436
  • 3
  • 5
2

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)")

}
Alvin George
  • 14,148
  • 92
  • 64
0

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];

0

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
}
Rozario Rapheal
  • 279
  • 1
  • 6
0

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;
Drey
  • 59
  • 1
  • 9
0

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)
}
Hari R Krishna
  • 782
  • 6
  • 20