Formatting seconds and minutes

2019-02-06 21:39发布

I need to format seconds and minutes from milliseconds. I am using countdownTimer. does anyone have sugestions? I looked at joda time. But all i need is a format so i have 1:05 and not 1:5. thanks

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();
}

标签: java time format
4条回答
三岁会撩人
2楼-- · 2019-02-06 22:16

A real lazy way of doing this as long as you know you won't have more than 60 minutes is to just make a date and use 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));
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-02-06 22:17

i'd use

org.apache.commons.lang.time.DurationFormatUtils.formatDuration(millisUntilFinished, "mm:ss")
查看更多
迷人小祖宗
4楼-- · 2019-02-06 22:32

You could do it using the standard Date formatting classes, but that might be a bit heavy-weight. I would just use the String.format method. For example:

int minutes = time / (60 * 1000);
int seconds = (time / 1000) % 60;
String str = String.format("%d:%02d", minutes, seconds);
查看更多
走好不送
5楼-- · 2019-02-06 22:34

I used Apache Commons StopWatch class. The default output of it's toString method is ISO8601-like, hours:minutes:seconds.milliseconds.

Example of Apache StopWatch

查看更多
登录 后发表回答