Convert a float into a time format mm:ss

跟風遠走 提交于 2019-12-13 05:09:38

问题


I'm searching a way with Objective-C to convert a float (audioPlayer.currentTime, which for example = 3.4592) into a time string with minutes and seconds (03:46)

I tried this:

static NSDateFormatter *date_formatter = nil;
if (date_formatter == nil) {
    date_formatter = [[NSDateFormatter alloc] init];
    [date_formatter setDateFormat:@"mm:ss"];
}
NSDate *diff = [[NSDate alloc] initWithTimeIntervalSinceNow:audioPlayer.currentTime];
NSLog(@"%@", [date_formatter stringFromDate:diff]);

... but that's not working. The format is correct but I can't find a way to correctly initialize the "diff" date.

Thanks for your help!


回答1:


You can convert float in to seconds like this

    double d = CMTimeGetSeconds(__avPlayer.currentItem.duration);

Then its matter of converting that into NSString for presentation below method might help you

- (NSString *) printSecond:(NSInteger) seconds {

    if (seconds < 60) {
        return [NSString stringWithFormat:@"00:%02d",seconds];
    }

    if (seconds >= 60) {

        int minutes = floor(seconds/60);
        int rseconds = trunc(seconds - minutes * 60);

        return [NSString stringWithFormat:@"%02d:%02d",minutes,rseconds];

    }

    return @"";

}


来源:https://stackoverflow.com/questions/19702538/convert-a-float-into-a-time-format-mmss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!