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.MINUTESand then check the minute-of-hour as per the requirement i.e. if it is not a multiple of5subtract the remainder when divided by5. UseLocalDate#withMinuteto return a copy of thisLocalDateTimewith the minute-of-hour altered.Output: