Skip to content
Advertisement

How to round off to the closest 5 minute interval if it is 1 or 2 minutes ahead or behind?

I want to round off an Instant / LocalDateTime to its closest 5 minutes interval in Java.

Examples: Suppose the time is: 2021-02-08T19:02:49.594 Expected result: 2021-02-08T19:00:00.000

Suppose the time is: 2021-02-08T19:03:49.594 Expected result: 2021-02-08T19:05:00.000

Similarly, if the time is: 2021-02-08T19:56:49.594 Expected result: 2021-02-08T19:55:00.000

Similarly, if the time is: 2021-02-08T19:58:49.594 Expected result: 2021-02-08T20:00:00.000

But if the time is 2021-02-08T19:55:00.000 or 2021-02-08T19:05:00.000 or 2021-02-08T19:00:00.000 then do nothing.

Advertisement

Answer

Here is a general-purpose solution (not just 5 minutes):

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement