PeriodFormatter not showing days

I use PeriodFormatter to return a string showing the time before the event. The code below stores the creation of strings such as 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() ); 
+5
source share
2 answers

This is because you convert Duration to Period using the Duratoin :: toPeriod method
This is described in the Joda documentation:

public Period toPeriod () Converts this duration to a Period instance using the standard period type and ISO timeline. Only exact fields in the period type. Thus, only an hour, a minute, in the second and milliseconds the fields will be used . Year, month, week and day will not be filled.

Period delay cannot be calculated correctly without a start date (or end date), as on some days it may be 24 hours or 23 hours (due to DST)

You use the Duration :: toPeriodFrom method instead
For instance.

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

As Ilya said by default, the toPeriod method will only fill in hours, minutes, seconds, and milliseconds . But you can normalize this with 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"); }: 
0
source

Source: https://habr.com/ru/post/1204392/


All Articles