Joda Time PeriodFormatterBuilder

Ste*_*fan 3 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?
   }
}
Run Code Online (Sandbox Code Playgroud)

打印出来:

 1 month 1 week 2 days 09 hours 56 minutes 21 seconds 
 1 month 2 days 09 hours 56 minutes 21 seconds
Run Code Online (Sandbox Code Playgroud)

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

Rea*_*tic 5

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

PeriodFormatter只打印领域,因为它们内部Period的对象。它不做任何计算。如果 days 字段是22即使您没有包括周数,它也会保留。

要获取在 days 字段而不是周字段中表示的周数,您应该创建一个具有不同类型的时间段:

Period periodWithoutWeeks = new Period(
     Date().getTime(),
     new DateTime(2014, 12, 25, 0, 0).getMillis(),
     PeriodType.yearMonthDayTime());
Run Code Online (Sandbox Code Playgroud)

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

Period periodWithoutWeeks =  period.normalizedStandard(PeriodType.yearMonthDayTime());
Run Code Online (Sandbox Code Playgroud)

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

System.out.println( f2.print(periodWithoutWeeks) );
Run Code Online (Sandbox Code Playgroud)