0

I am getting time from Google server as PT4M30S,PT7M2S. If it is first one, ie PT4M30S ,then I displayed it as 4:30.But second one is coming like this 7:2, which I don't want.I like it to be like 7:02.

This is what I did some how

 NSString *m=@"M";                                         
     NSString *s=@"S";
    NSRange rang =[videoTimeString rangeOfString:m options:NSCaseInsensitiveSearch];                 
if(rang.length==[m length])
   {
      if(rang.length==[s length])
    {
      NSString *string1=[videoTimeString stringByReplacingOccurrencesOfString:@"PT" withString:@""];
    NSString *string2=[string1 stringByReplacingOccurrencesOfString:@"M" withString:@":"];
    finalTime=[string2 stringByReplacingOccurrencesOfString:@"S" withString:@""];}
     else{
     NSString *string1=[videoTimeString stringByReplacingOccurrencesOfString:@"PT" withString:@""];
                        finalTime=[string1 stringByReplacingOccurrencesOfString:@"M" withString:@":00"];

                      }
                    }
                else{
                    NSString *string1=[videoTimeString stringByReplacingOccurrencesOfString:@"PT" withString:@"0:"];
                    finalTime=[string1 stringByReplacingOccurrencesOfString:@"S" withString:@""];
    }

So any help would be appreciated.

Thanks

4

1 に答える 1

1

以下のメソッドは、 の形式の文字列を受け取り、PT7M2Sそれを に変換し7:02ます。

- (NSString *)parseGoogleTime:(NSString *)time
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"PT(\\d+)M(\\d+)S"
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    if (error) {
        return nil;
    }

    NSArray *matches = [regex matchesInString:time options:0 range:NSMakeRange(0, time.length)];
    if (matches.count == 0) {
        return nil;
    }

    NSTextCheckingResult *match = matches[0];
    NSMutableString *parsedTime = [NSMutableString string];

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];

    for (NSUInteger i = 1; i < match.numberOfRanges; i++) {
        NSString *substringForMatch = [time substringWithRange:[match rangeAtIndex:i]];
        NSInteger timePart = [[formatter numberFromString:substringForMatch] integerValue];
        [parsedTime appendFormat:i == 1 ? @"%i:" : @"%02i", timePart];
    }

    return parsedTime;
}
于 2013-10-08T11:38:40.457 に答える