【问题标题】:Formatting seconds and minutes格式化秒和分钟
【发布时间】:2012-09-10 04:46:00
【问题描述】:

我需要从毫秒格式化秒和分钟。我正在使用倒数计时器。有人有建议吗?我看了乔达时间。但我需要的只是一种格式,所以我有 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();
}

【问题讨论】:

  • 您是否已经研究过 SimpleNumberFormat?或者,如果整数小于 10,您始终可以在整数左侧附加一个“0”。
  • 我不确定它是否能满足您的全部需求,但可能值得一看 PrettyTime

标签: java time format


【解决方案1】:

您可以使用标准的日期格式化类来做到这一点,但这可能有点重。我只会使用 String.format 方法。例如:

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

【讨论】:

  • 太棒了!这正是我要找的!我不确定我是否理解“%d:%02d”,我自己尝试过,但没有做对。谢谢!
  • % 表示替换,0 表示零填充数字,2 表示宽度为 2,d 表示显示为十进制数。这是文档:docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
【解决方案2】:

只要您知道自己的时间不会超过 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));
}

【讨论】:

  • 不错的答案!我喜欢你提到的需要将dateFormat.setTimeZone 设置为格林威治标准时间。这很重要。
【解决方案3】:

我会用

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

【讨论】:

    【解决方案4】:

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

    Example of Apache StopWatch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多