Rounding up milliseconds when printing with Joda Time

Posted by RoToRa on Stack Overflow See other posts from Stack Overflow or by RoToRa
Published on 2010-05-06T12:16:52Z Indexed on 2010/05/06 16:38 UTC
Read the original article Hit count: 270

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about jodatime