Joda Time PeriodFormatterBuilder

时间:2014-11-14 13:20:30

标签: java jodatime

我刚刚在Joda Time框架中测试了PeriodFormatterBuilder。当我将周输出附加到构建器时,计算的时间是正确的。但如果没有追加周数,实际上我想要的是什么,那么建造者只需要7天就可以了:

public class JodaTest {
  public static void main(String[] args) {

    // builder 1 (weeks inc.)
    PeriodFormatterBuilder b1 = new PeriodFormatterBuilder();
    b1.appendYears().appendSuffix(" year", " years");
    b1.appendSeparator(" ");
    b1.appendMonths().appendSuffix(" month", " months");
    b1.appendSeparator(" ");
    // appends weeks ...
    b1.appendWeeks().appendSuffix(" week", " weeks");
    b1.appendSeparator(" ");
    b1.appendDays().appendSuffix(" day", " days");
    b1.appendSeparator(" ");
    b1.printZeroIfSupported().minimumPrintedDigits(2);
    b1.appendHours().appendSuffix(" hour", " hours");
    b1.appendSeparator(" ");
    b1.appendMinutes().appendSuffix(" minutes");
    b1.appendSeparator(" ");
    b1.appendSeconds().appendSuffix(" seconds");
    PeriodFormatter f1 = b1.toFormatter();

    // builder 2 (weeks not inc.)
    PeriodFormatterBuilder b2 = new PeriodFormatterBuilder();
    b2.appendYears().appendSuffix(" year", " years");
    b2.appendSeparator(" ");
    b2.appendMonths().appendSuffix(" month", " months");
    b2.appendSeparator(" ");
    // does not append weeks ...
    b2.appendDays().appendSuffix(" day", " days");
    b2.appendSeparator(" ");
    b2.printZeroIfSupported().minimumPrintedDigits(2);
    b2.appendHours().appendSuffix(" hour", " hours");
    b2.appendSeparator(" ");
    b2.appendMinutes().appendSuffix(" minutes");
    b2.appendSeparator(" ");
    b2.appendSeconds().appendSuffix(" seconds");
    PeriodFormatter f2 = b2.toFormatter();

    Period period = new Period(new Date().getTime(), new DateTime(2014, 12, 25, 0, 0).getMillis());

    System.out.println(f1.print(period));
    System.out.println(f2.print(period)); // 7 days missing?
   }
}

打印出来:

 1 month 1 week 2 days 09 hours 56 minutes 21 seconds 
 1 month 2 days 09 hours 56 minutes 21 seconds

在第二行中,日值应为“9天”。如何使构建器汇总正确的日期值?

1 个答案:

答案 0 :(得分:4)

标准Period对象将句点分为年,月,周,日和时间字段。超过一周的持续时间将添加到weeks字段,days字段或多或少是将持续时间除以7的剩余部分。

PeriodFormatter仅打印Period对象内的字段。它没有做任何计算。如果天数字段为2,则即使您未包含周数,它也会保留2

要获取包含在days字段而不是周字段中的周数的句点,您应该创建一个具有不同类型的句点:

Period periodWithoutWeeks = new Period(
     Date().getTime(),
     new DateTime(2014, 12, 25, 0, 0).getMillis(),
     PeriodType.yearMonthDayTime());

或者假设一周是标准的7天,将您的期间转换为没有周数的类型:

Period periodWithoutWeeks =  period.normalizedStandard(PeriodType.yearMonthDayTime());

现在您可以使用任一格式化程序打印它:

System.out.println( f2.print(periodWithoutWeeks) );