0

我从 Google 服务器获取时间为PT4M30S,PT7M2S. 如果是第一个,即PT4M30S,那么我将其显示为4:30。但是第二个是这样来的7:2,我不想要。我喜欢它7:02

这就是我做了一些如何

 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:@""];
    }

所以任何帮助将不胜感激。

谢谢

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 回答