我从谷歌服务器获得时间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:@""];
}
因此,任何帮助将不胜感激。
谢谢
下面的方法将获取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;
}