我需要创建一个具有以下签名的方法:
public String getPrintTime (int t);
t表示时间,以毫秒为单位,范围为1-5120000。输出需要采用MM:ss:mmm格式。例如:
getPrintTime(2342819) == 39:02.819
getPrintTime(23) == 00:00.023
getPrintTime(2340000) == 39:00.000
我在很多方面尝试过,但在所有情况下都无法使用它。
你可以使用SimpleDateFormat
。但请注意,正确的格式字符串不是MM:ss.mmm
而是mm:ss.SSS
。
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss.SSS");
String formatted = sdf.format(new Date(t));
或者,用简单的除法,模数和String.format滚动你自己:
int minutes = t /(1000 * 60);
int seconds = t / 1000 % 60;
int millis = t % 1000;
String formatted = String.format("%02d:%02d.%03d", minutes, seconds, millis);