PeriodFormatter not showing days

柔情痞子 提交于 2019-12-07 03:54:03

问题


I am using a PeriodFormatter to return a string showing the time until an event. The code below keeps creating strings like 1146 hours 39 minutes instead of x days y hours z minutes. Any ideas?

Thanks, Nathan

   PeriodFormatter formatter = new PeriodFormatterBuilder()
                .printZeroNever()
                .appendDays()
                .appendSuffix( "d " )
                .appendHours()
                .appendSuffix( "h " )
                .appendMinutes()
                .appendSuffix( "m " )
                .toFormatter();
        return formatter.print( duration.toPeriod() );

回答1:


This is because you convert Duration to Period with method Duratoin::toPeriod
This is described in Joda-time documentation:

public Period toPeriod() Converts this duration to a Period instance using the standard period type and the ISO chronology. Only precise fields in the period type will be used. Thus, only the hour, minute, second and millisecond fields on the period will be used. The year, month, week and day fields will not be populated.

Period insance cann't be calculated properly without start date (or end date), because some days can be 24h or 23h (due to DST)

You shoud use method Duration::toPeriodFrom method instead
E.g.

Duration duration = new Duration(date1, date2);  
// ...  
formatter.print( duration.toPeriodFrom(date1));



回答2:


As Ilya said by default the toPeriod method will only populate hour, minute, second and millisecond fields. But you can actually normalize that back using normalizedStandard so that

String periodFormat(Duration d) {
    return PERIOD_FORMATTER.print(d.toPeriod().normalizedStandard());
}

static final PeriodFormatter PERIOD_FORMATTER = new PeriodFormatterBuilder()
  .appendWeeks().appendSuffix("w")
  .appendSeparator("_")
  .printZeroRarelyLast()

  .appendDays().appendSuffix("d")
  .appendSeparator("_")
  .printZeroRarelyLast()

  .appendHours().appendSuffix("h")
  .appendSeparator("_")
  .printZeroRarelyLast()

  .appendMinutes().appendSuffix("m")
  .appendSeparator("_")
  .printZeroRarelyLast()

  .toFormatter();

Will pass

  @Test
  public void periodFormatTest {
    assertThat(periodFormat(Duration.standardMinutes(5))).isEqualTo("5m");
    assertThat(periodFormat(Duration.standardMinutes(60))).isEqualTo("1h");
    assertThat(periodFormat(Duration.standardDays(1))).isEqualTo("1d");
    assertThat(periodFormat(Duration.standardDays(2))).isEqualTo("2d");
    assertThat(periodFormat(Duration.standardHours(47))).isEqualTo("1d_23h");

  }:


来源:https://stackoverflow.com/questions/26291271/periodformatter-not-showing-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!