Search code examples
javaandroidtimesecondstimeunit

Java - change Minutes and Seconds to time format? (mm:ss)


i started with total milliseconds, which I've converted to to total minutes and total seconds:

long minutes = TimeUnit.MILLISECONDS.toMinutes(itemDuration);
long seconds = TimeUnit.MILLISECONDS.toSeconds(itemDuration)
     - TimeUnit.MINUTES.toSeconds(minutes);

Now I want to display the minutes and seconds in a mm:ss format (and if occasionally there are hours, then convert to hh:mm:ss format). how would i go about doing this?

thanks!

edit: I've tried using SimpleDateFormat, however it would display the wrong time in time zone that differ by half an hour vs a full hour. (ie: if the time zone was GMT +5:30 and the item duraction was 5 seconds, the app would display 30:05 instead of 00:05).. however it works fine for other time zones that differ by a full hour, such as GMT+5.

unless i'm doing something wrong with the SimpleDateFormat?

private static final SimpleDateFormat mLengthFormatter = new SimpleDateFormat("mm:ss", Locale.getDefault());

(also, just out of curiosity, if I use a SimpleDateFormat, and the number of minutes is greater than 2 digits, then what would happen? would it max out at 99?)


Solution

  • Could probably do it with a string formatter.

    formatter.format("%2d:%2d", minutes,seconds);