I'm implementing a count-down using Joda Time. I only need a display accuracy of seconds.
However when printing the time, the seconds are displayed as full seconds, so when the count down reaches, for example, 900ms, then "0" seconds is printed, but as a count-down it would make more sense to display "1" second, until the time actually reaches 0ms.
Example:
void printDuration(Duration d) {
  System.out.println(
    d.toPeriod(PeriodType.time()).toString(
      new PeriodFormatterBuilder().printZeroAlways().appendSeconds().toFormatter()
    )
  );
}
printDuration(new Duration(5000)); // Prints "5" => OK
printDuration(new Duration(4900)); // Prints "4" => need "5"
printDuration(new Duration(1000)); // Prints "1" => OK
printDuration(new Duration(900));  // Prints "0" => need "1"
printDuration(new Duration(0));    // Prints "0" => OK
Basically I need to the seconds to be display rounded up from milliseconds and not rounded down. Is there a way to achieve this with Joda without needing to write my own formatter?
The simplest way would be to take the existing duration, round the milliseconds appropriately to create a new duration, and format that:
private static Duration roundToSeconds(Duration d) {
  return new Duration(((d.getMillis() + 500) / 1000) * 1000);
}
(Note that this assumes positive durations, otherwise the rounding will be odd.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With