Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JodaTime: Print Period with Days as Hours?

Tags:

java

jodatime

Is there any way to create a PeriodFormatter in JodaTime which is able to print a Period of lets say 2 days, 4 hours and 4 minutes as 52 hours, 4 minutes?

like image 731
t3chris Avatar asked May 23 '11 08:05

t3chris


1 Answers

I believe you can use Period.normalizedStandard specifying a PeriodType containing just hours and minutes. Sample:

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        // 2 days, 4 hours, 4 minutes
        Period period = new Period(0, 0, 0, 2, 4, 4, 0, 0);

        // Actually we're fine with seconds etc as well
        Period hoursAndMinutes = period.normalizedStandard(PeriodType.time());

        PeriodFormatter formatter = new PeriodFormatterBuilder()
            .appendHours()
            .appendSuffix(" hour", " hours")
            .appendMinutes()
            .appendSuffix(" minute", " minutes")
            .toFormatter();
        System.out.println(formatter.print(hoursAndMinutes));
    }
}
like image 73
Jon Skeet Avatar answered Sep 22 '22 11:09

Jon Skeet