Skip to content

Instantly share code, notes, and snippets.

@klausbrunner
Last active February 22, 2025 10:04
Show Gist options
  • Save klausbrunner/7c9b064f4d3baf7455b9ddb3804462e7 to your computer and use it in GitHub Desktop.
Save klausbrunner/7c9b064f4d3baf7455b9ddb3804462e7 to your computer and use it in GitHub Desktop.
Using a TemporalAdjuster to round a time to the actual nearest minute, i.e. rounding to floor or ceiling as appropriate. While truncation (rounding to floor) is part of the standard Java API and also implicitly done when formatting only hours and minutes, rounding up or down to the nearest minute is not.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.LocalTime;
import java.time.temporal.*;
import org.junit.jupiter.api.Test;
class NearestMinuteTest {
/**
* Adjusts given Temporal object to the <em>nearest</em> minute (rounding up from 30 seconds),
* assuming it has the necessary field (SECOND_OF_MINUTE). This includes at least Local(Date)Time,
* Offset(Date)Time, Zoned(Date)Time.
*/
public static final TemporalAdjuster NEAREST_MINUTE =
(t) -> {
if (t.get(ChronoField.SECOND_OF_MINUTE) >= 30) {
t = t.plus(1, ChronoUnit.MINUTES);
}
return t.with(ChronoField.SECOND_OF_MINUTE, 0).with(ChronoField.NANO_OF_SECOND, 0);
};
@Test
public void tests() {
LocalTime lt = LocalTime.of(13, 59, 30, 0);
assertEquals(LocalTime.of(14, 0, 0), lt.with(NEAREST_MINUTE));
lt = LocalTime.of(13, 59, 30, 1);
assertEquals(LocalTime.of(14, 0, 0), lt.with(NEAREST_MINUTE));
lt = LocalTime.of(13, 59, 29, 999_999_999);
assertEquals(LocalTime.of(13, 59, 0), lt.with(NEAREST_MINUTE));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment