Period to string [duplicate]

You need to normalize the period because if you construct it with the total number of seconds, then that’s the only value it has. Normalizing it will break it down into the total number of days, minutes, seconds, etc.

Edit by ripper234 – Adding a TL;DR version: PeriodFormat.getDefault().print(period)

For example:

public static void main(String[] args) {
  PeriodFormatter daysHoursMinutes = new PeriodFormatterBuilder()
    .appendDays()
    .appendSuffix(" day", " days")
    .appendSeparator(" and ")
    .appendMinutes()
    .appendSuffix(" minute", " minutes")
    .appendSeparator(" and ")
    .appendSeconds()
    .appendSuffix(" second", " seconds")
    .toFormatter();

  Period period = new Period(72, 24, 12, 0);

  System.out.println(daysHoursMinutes.print(period));
  System.out.println(daysHoursMinutes.print(period.normalizedStandard()));
}

Will print:

24 minutes and 12 seconds
3 days and 24 minutes and 12 seconds

So you can see the output for the non-normalized period simply ignores the number of hours (it didn’t convert the 72 hours to 3 days).

Leave a Comment