Matt Finnegan
Matt Finnegan

Reputation: 1

Format NSTimeInterval as Minutes:Seconds:milliseconds

Can anyone please tell me how to display milliseconds in this piece of code?

-(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];
}

Upvotes: 0

Views: 3095

Answers (3)

rob mayoff
rob mayoff

Reputation: 386038

I think this is the simplest solution:

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

That formats the time as MM:SS.sss. If you really want it as MM:SS:sss (which I don't recommend), you can do this:

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

Note that stringWithFormat: does not require nil at the end of its argument list.

Upvotes: 0

SALMAN
SALMAN

Reputation: 2031

[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]; 
}

If any wants milliseconds to max 60 than edit this line

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

to

int millisec = ((milli) % 60);

Upvotes: 1

CIFilter
CIFilter

Reputation: 8667

I don't understand. Don't you just have to create a new variable for the milliseconds?

NSInteger milliseconds = (sec * 1000);

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

Upvotes: 0

Related Questions