获取音频持续时间字符串为浮点值

时间:2016-12-26 09:50:40

标签: ios objective-c

{
     duration = "00:06:29";
     id = 7;
}

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;

float value = [numberFormatter numberFromString:currentAutio.duration].floatValue;
NSLog(@"Current audio %f",value);

out 当前音频0.0000

如何将持续时间字符串设为浮点值?

1 个答案:

答案 0 :(得分:2)

最简单的方法是

NSString *duration = @"00:06:29";
NSArray *array = [duration componentsSeparatedByString:@":"];

NSLog(@"Current hrs %ld",(long)[(NSString *)(array[0]) integerValue]);
NSLog(@"Current min %ld",(long)[(NSString *)(array[1]) integerValue]);
NSLog(@"Current sec %ld",(long)[(NSString *)(array[2]) integerValue]);

否则您可以使用NSDate& NSDateFormatter也是如此。

修改

使用NSDate,请注意小时部分不应超过23,否则结果可能与预期不符。

NSString *duration = @"00:06:29";

NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"HH:mm:ss";

NSDate *date = [formatter dateFromString:duration];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date];
NSLog(@"hrs %ld", (long)components.hour);
NSLog(@"min %ld", (long)components.minute);
NSLog(@"sec %ld", (long)components.second);