Formatting seconds and minutes

I need to format seconds and minutes from milliseconds. I am using countdownTimer. Does anyone have any suggestions? I looked at Joda's time. But all I need is a format, so I have 1:05, 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();
}
+5
source share
4 answers

You can do this using standard date formatting classes, but it can be a bit overwhelming. I would just use the String.format method. For instance:

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

A real lazy way to do this, as long as you know that you won't have more than 60 minutes, you just need to 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));
}
+6
source

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

I used the Apache Commons StopWatch class. By default, its toString method has ISO8601-like, hours: minutes: seconds.milliseconds.

Apache StopWatch Example

0
source

All Articles