将秒转换为人类可读格式MM:SS Java

Bel*_*ish 4 java format time string-formatting

如何将long int of seconds转换为人类可读的格式

MM:SS
Run Code Online (Sandbox Code Playgroud)

只有SS应填0,所以

long = 67 -> 1:07
Run Code Online (Sandbox Code Playgroud)

Bhe*_*ung 10

String readable = String.format("%d:%02d", s/60, s%60);
Run Code Online (Sandbox Code Playgroud)

  • +1这更优雅! (2认同)

Ada*_*ost 2

使用整数除以 60 将秒转换为整分钟。秒除以 60 的模数 (%) 将给出“剩余”秒数。然后使用字符串转换来检查 0 填充的必要性。

int minutes = (total / 60);
int seconds = (total % 60);
String secs = Integer.toString(seconds);
if (seconds < 10) {
   secs = "0" + seconds;
}
String time = minutes + ":" + secs;
Run Code Online (Sandbox Code Playgroud)