fedor.belov
fedor.belov

Reputation: 23323

Convert JodaTime duration to string

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

Upvotes: 27

Views: 12155

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79095

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.

Upvotes: 1

Yokich
Yokich

Reputation: 1326

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!

Upvotes: 28

Ilya
Ilya

Reputation: 29693

Duration yourDuration = //...
Period period = yourDuration.toPeriod();
PeriodFormatter minutesAndSeconds = new PeriodFormatterBuilder()
     .printZeroAlways()
     .appendMinutes()
     .appendSeparator(":")
     .appendSeconds()
     .toFormatter();
String result = minutesAndSeconds.print(period);

Upvotes: 32

Related Questions