格式化秒和分钟

我需要从毫秒开始格式化秒和分钟。 我正在使用countdownTimer。 有没有人有吸烟? 我看着乔达时间。 但我需要的是一种格式,所以我有1:05而不是1:5。 谢谢

private void walk() { new CountDownTimer(15000, 1000) { @Override public void onFinish() { lapCounter++; lapNumber.setText("Lap Number: " + lapCounter); run(); } @Override public void onTick(long millisUntilFinished) { text.setText("Time left:" + millisUntilFinished/1000); } }.start(); } 

您可以使用标准的日期格式化类来完成它,但这可能有点重量级。 我只想使用String.format方法。 例如:

 int minutes = time / (60 * 1000); int seconds = (time / 1000) % 60; String str = String.format("%d:%02d", minutes, seconds); 

只要你知道你不会超过60分钟,这是一个真正的懒惰方式就是只做一个日期并使用SimpleDateFormat

 public void onTick(long millisUntilFinished) { SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = new Date(millisUntilFinished); text.setText("Time left:" + dateFormat.format(date)); } 

我会用的

 org.apache.commons.lang.time.DurationFormatUtils.formatDuration(millisUntilFinished, "mm:ss") 

我使用了Apache Commons StopWatch类。 它的toString方法的默认输出是ISO8601,小时:分钟:秒。毫秒。

Apache StopWatch的示例