创建一个带有前导零的NSString,分钟和秒

Pra*_*ypa 2 string formatting cocoa cocoa-touch objective-c

我需要不断更新标签中的播放时间.我得到的时间NSTimeInterval currentProgress = self.moviePlayerController.currentPlaybackTime;返回一个double值.但我需要显示的格式是"MM:SS"(00:00).我试过以下代码

NSTimeInterval currentProgress = self.moviePlayerController.currentPlaybackTime;

float min = floor(currentProgress/60);
float sec = round(currentProgress - min * 60);
Run Code Online (Sandbox Code Playgroud)

当进度时间为10分10秒时,显示完全正常,如"10:10".但问题是如果进度时间是1分7秒,它会在标签中显示"1:7".我想要的展示是"01:07".我怎样才能做到这一点?

Ole*_*man 8

NSString *time = [NSString stringWithFormat:@"%02d:%02d", (int)min, (int)sec];
Run Code Online (Sandbox Code Playgroud)

试试这个.应该工作!


dre*_*lax 5

这应该做的伎俩:

int seconds = (int)currentProgress % 60;
int minutes = currentProgress / 60;

NSString *result = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
Run Code Online (Sandbox Code Playgroud)

%02d格式说明以0使得场作为将自动垫至少宽2个字符.