I want to convert Java 8 LocalDateTime to nearest 5 minutes. E.g.
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 existing functionality of LocalDateTime or Math api. Any suggestions?
You can round towards 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 nanos only once as they stay zero).
Alternatively to what Holger suggests, you can create a TemporalAdjuster
, which will allow 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(1d * minute / minutes) * minutes;
int adjustBy = nearestMinute - minute;
return temporal.plus(adjustBy, ChronoUnit.MINUTES);
};
}
Note that this doesn't truncate the seconds/nanos from the original date. If you want that, you can amend the end of the adjuster to:
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);
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