My PeriodFormatter does not behave as I expect - what did I do wrong?

I'm having problems using Jode Time PeriodFormatter. I want days, hours, minutes and seconds to be reported, but my attempt seems to be wrapping around weeks. What should I do differently?

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

public class Problems {

    public static void main(String[] args) {

        PeriodFormatter formatter = new PeriodFormatterBuilder()
            .printZeroNever()
            .appendDays()
            .appendSuffix(" day", " days")
            .appendSeparator(", ")
            .appendHours()
            .appendSuffix(" hour", " hours")
            .appendSeparator(", ")
            .appendMinutes()
            .appendSuffix(" minute", " minutes")
            .appendSeparator(", ")
            .appendSeconds()
            .appendSuffix(" second", " seconds")
            .toFormatter();

        DateTime now = new DateTime();
        DateTime justUnderAWeekAgo = now.minusDays(7).plusMinutes(1);
        DateTime justOverAWeekAgo = now.minusDays(7).minusMinutes(1);
        System.out.println(now);
        System.out.println(justUnderAWeekAgo);
        System.out.println(justOverAWeekAgo);
        // I am happy with the following:
        System.out.println(
            formatter.print(new Period(justUnderAWeekAgo, now)));
        // But not with this (outputs "1 minute" but I want "7 days, 1 minute"):
        System.out.println(
            formatter.print(new Period(justOverAWeekAgo, now)));
    }
}

EDIT: I think I can understand why this does not work - that is, that the formatter simply prints the different values ​​of the Period, and since Periods keep the value for weeks, the value for the days on my problem period is really 0. But I have everything still need a good way to do this ...

+5
source share
1 answer

, PeriodFormatter .

:

1: :

PeriodFormatter formatter = new PeriodFormatterBuilder()
        .printZeroNever()
        .appendWeeks()
        .appendSuffix(" week", " weeks")
        .appendSeparator(", ")
        .appendDays()
        .appendSuffix(" day", " days")
        .appendSeparator(", ")
        .appendHours()
        .appendSuffix(" hour", " hours")
        .appendSeparator(", ")
        .appendMinutes()
        .appendSuffix(" minute", " minutes")
        .appendSeparator(", ")
        .appendSeconds()
        .appendSuffix(" second", " seconds")
        .toFormatter();

:

1 week, 1 minute

2. , PeriodType.yearMonthDayTime():

new Period(justUndeAWeekAgo, now, PeriodType.yearMonthDayTime());

, PeriodFormatter , . :

7 days, 1 minute
+12

All Articles