Rounding milliseconds when printing with Joda Time

I am using a countdown using Joda Time. I only need the accuracy of the display of seconds.

However, when printing the time, seconds are displayed as full seconds, so when the countdown reaches, for example, 900 ms, then “0” seconds are printed, but as a countdown it makes sense to display “1” seconds until the time reaches 0 ms.

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 the seconds to be displayed rounded from milliseconds and not rounded. Is there a way to achieve this with Joda without requiring you to write your own formatter?

+3
source share
3 answers

:

private static Duration roundToSeconds(Duration d) {
  return new Duration(((d.getMillis() + 500) / 1000) * 1000);
}

( , , .)

+3

?

, printDuration ( 0 Duration(60000) - )

(, , )

, ( "3600" ), , :

static void printDuration(Duration d) {
      int secs = (int)((d.getMillis()+999)/1000); 
      System.out.println(secs);
}

, .

+1
import java.math.BigDecimal;

private Duration round(Duration d) {
  return Duration.standardSeconds(new BigDecimal(d.getMillis()).divide(1000, 0, BigDecimal.ROUND_up));
}

:

void printDuration(Duration d) {
    System.out.println(
        round(d).toPeriod(PeriodType.time()).toString(
            new PeriodFormatterBuilder().printZeroAlways().appendSeconds().toFormatter()
        )
    );
}
0
source

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


All Articles