I want to round down an Instant / LocalDateTime to its closest 5 minutes interval in Java.
Examples: Suppose the time is:
2021-02-08T19:01:49.594
or
2021-02-08T19:02:49.594
or
2021-02-08T19:03:49.594
or
2021-02-08T19:04:49.594
Expected result:
2021-02-08T19:00:00.000
You can truncate it to ChronoUnit.MINUTES
and then check the minute-of-hour as per the requirement i.e. if it is not a multiple of 5
subtract the remainder when divided by 5
. Use LocalDate#withMinute
to return a copy of this LocalDateTime
with the minute-of-hour altered.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
class Main {
public static void main(String[] args) {
// Test
String[] arr = { "2021-02-08T19:02:49.594", "2021-02-08T19:56:49.594", "2021-02-08T19:54:49.594",
"2021-02-08T19:06:49.594" };
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS");
for (String s : arr) {
System.out.println(roundToNearestHour(s).format(dtf));
}
}
static LocalDateTime roundToNearestHour(String str) {
LocalDateTime ldt = LocalDateTime.parse(str).truncatedTo(ChronoUnit.MINUTES);
int minute = ldt.getMinute();
int remainder = minute % 5;
if (remainder != 0) {
ldt = ldt.withMinute(minute - remainder);
}
return ldt;
}
}
Output:
2021-02-08T19:00:00.000
2021-02-08T19:55:00.000
2021-02-08T19:50:00.000
2021-02-08T19:05:00.000