我在使用Joda Time的PeriodFormatter时遇到麻烦。我想报告几天,几小时,几分钟和几秒钟,但是我的尝试似乎在数周之内。我应该怎么做?

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)));
    }
}

编辑:我想我可以理解为什么它不起作用-即格式化程序仅打印Period的各种值,并且由于Periods存储了数周的值,因此我的问题期内的天数确实为0。但是我仍然需要一个很好的方法来做到这一点...

最佳答案

您遇到的问题是您不要求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

09-26 20:37