Java 8 LocalDateTime is rounded to the next X minutes

I want to convert Java 8 LocalDateTime in the next 5 minutes. For instance.

1601  ->  1605
1602  ->  1605
1603  ->  1605
1604  ->  1605
1605  ->  1605
1606  ->  1610
1607  ->  1610
1608  ->  1610
1609  ->  1610
1610  ->  1610

I would like to use the existing LocalDateTime or Math api functions. Any suggestions?

+5
source share
2 answers

You can round to the next multiple of five minutes using:

LocalDateTime dt = …
dt = dt.withSecond(0).withNano(0).plusMinutes((65-dt.getMinute())%5);

You can reproduce your example using

LocalDateTime dt=LocalDateTime.now().withHour(16).withSecond(0).withNano(0);
for(int i=1; i<=10; i++) {
    dt=dt.withMinute(i);
    System.out.printf("%02d%02d -> ", dt.getHour(), dt.getMinute());
    // the rounding step:
    dt=dt.plusMinutes((65-dt.getMinute())%5);
    System.out.printf("%02d%02d%n", dt.getHour(), dt.getMinute());
}

1601 -> 1605
1602 -> 1605
1603 -> 1605
1604 -> 1605
1605 -> 1605
1606 -> 1610
1607 -> 1610
1608 -> 1610
1609 -> 1610
1610 -> 1610

(in this example, I clear the seconds and nano only once when they remain equal to zero).

+7
source

As an alternative to what Holger offers, you can create TemporalAdjusterone that allows you to write something like date.with(nextOrSameMinutes(5)):

public static void main(String[] args) {
  for (int i = 0; i <= 10; i++) {
    LocalDateTime d = LocalDateTime.of(LocalDate.now(), LocalTime.of(16, i, 0));
    LocalDateTime nearest5 = d.with(nextOrSameMinutes(5));
    System.out.println(d.toLocalTime() + " -> " + nearest5.toLocalTime());
  }
}

public static TemporalAdjuster nextOrSameMinutes(int minutes) {
  return temporal -> {
    int minute = temporal.get(ChronoField.MINUTE_OF_HOUR);
    int nearestMinute = (int) Math.ceil(minute / 5d) * 5;
    int adjustBy = nearestMinute - minute;
    return temporal.plus(adjustBy, ChronoUnit.MINUTES);
  };
}

, / . , :

if (adjustBy == 0
        && (temporal.get(ChronoField.SECOND_OF_MINUTE) > 0 || temporal.get(ChronoField.NANO_OF_SECOND) > 0)) {
  adjustBy += 5;
}
return temporal.plus(adjustBy, ChronoUnit.MINUTES)
          .with(ChronoField.SECOND_OF_MINUTE, 0)
          .with(ChronoField.NANO_OF_SECOND, 0);
+5

All Articles