27

I have movie with duration 127 seconds. I wanna display it as 02:07. What is the best way to implement this?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
fedor.belov
  • 22,343
  • 26
  • 89
  • 134

3 Answers3

32
Duration yourDuration = //...
Period period = yourDuration.toPeriod();
PeriodFormatter minutesAndSeconds = new PeriodFormatterBuilder()
     .printZeroAlways()
     .appendMinutes()
     .appendSeparator(":")
     .appendSeconds()
     .toFormatter();
String result = minutesAndSeconds.print(period);
Ilya
  • 29,135
  • 19
  • 110
  • 158
27

I wanted this for myself and I did not find llyas answer to be accurate. I want to have a counter and when I had 0 hours and 1 minute I got 0:1 with his answer- but this is fixed easily with one line of code!

Period p = time.toPeriod();
PeriodFormatter hm = new PeriodFormatterBuilder()
    .printZeroAlways()
    .minimumPrintedDigits(2) // gives the '01'
    .appendHours()
    .appendSeparator(":")
    .appendMinutes()
    .toFormatter();
String result = hm.print(p);

This will give you 02:07!

Pang
  • 9,564
  • 146
  • 81
  • 122
Yokich
  • 1,247
  • 1
  • 17
  • 31
1

java.time

Quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern date-time API

You can use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenience methods were introduced.

Demo:

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        Duration duration = Duration.ofSeconds(127);
        // Default format
        System.out.println(duration);

        // Custom format
        // ####################################Java-8####################################
        String formattedElapsedTime = String.format("%02d:%02d", duration.toMinutes(), duration.toSeconds() % 60);
        System.out.println(formattedElapsedTime);
        // ##############################################################################

        // ####################################Java-9####################################
        formattedElapsedTime = String.format("%02d:%02d", duration.toMinutesPart(),
                duration.toSecondsPart());
        System.out.println(formattedElapsedTime);
        // ##############################################################################
    }
}

Output:

PT2M7S
02:07
02:07

Online Demo

Learn about the modern date-time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110