将NSTimeInterval格式化为分钟:秒:毫秒

时间:2011-09-20 03:37:48

标签: ios objective-c nstimeinterval

有人可以告诉我如何在这段代码中显示毫秒数吗?

-(void)updateViewForPlayerInfo:(AVAudioPlayer*)p {
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateTimeLeft)userInfo:p repeats:YES];
}

- (void)updateTimeLeft {
    NSTimeInterval timeLeft = player.duration - player.currentTime;

    int min=timeLeft / 60;
    int sec=lroundf(timeLeft) % 60;

    durationLabel.text = [NSString stringWithFormat:@"-%02d:%02d",min,sec,nil];
}

3 个答案:

答案 0 :(得分:1)

[NSTimer scheduledTimerWithTimeInterval:0.0167 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

-(void)updateTimer {
    countDownTotalTimer++;     
    TotalTime.text=[self timeFormatted:countDownTotalTimer];
}

- (NSString *)timeFormatted:(int)milli
{
    int millisec = ((milli) % 60)+39; 
    int sec = (milli / 60) % 60; 
    int min = milli / 3600; 

    return [NSString stringWithFormat:@"%02d:%02d:%02d",min, sec, millisec]; 
}

如果有人想要毫秒到最多60分钟而不是编辑这一行

int millisec = ((milli) % 60)+39;  

int millisec = ((milli) % 60);

答案 1 :(得分:0)

我不明白。你不必只需要创建一个毫秒的新变量吗?

NSInteger milliseconds = (sec * 1000);

durationLabel.text = [NSString stringWithFormat:@"-%02d:%02d.%04d",min,sec, milliseconds, nil];

答案 2 :(得分:0)

我认为这是最简单的解决方案:

durationLabel.text = [NSString stringWithFormat:@"-%02d:%06.3f",
    (int)(timeLeft / 60), fmod(timeLeft, 60)];

将时间格式化为MM:SS.sss。如果你真的想要它MM:SS:sss(我不推荐),你可以这样做:

durationLabel.text = [NSString stringWithFormat:@"-%02d:%02d:%03.0f",
    (int)(timeLeft / 60), (int)fmod(timeLeft, 60), 1000*fmod(timeLeft, 1)];

请注意,stringWithFormat:在其参数列表的末尾不需要nil