The java.time
API does not support rounding to ceiling, however it does support rounding to floor (truncation) which enables the desired behaviour (which isn't exactly rounding to ceiling):
LocalDateTime now = LocalDateTime.now();
LocalDateTime roundFloor = now.truncatedTo(ChronoUnit.MINUTES);
LocalDateTime roundCeiling = now.truncatedTo(ChronoUnit.MINUTES).plusMinutes(1);
In addition, there is a facility to obtain a clock that only ticks once a minute, which may be of interest:
Clock minuteTickingClock = Clock.tickMinutes(ZoneId.systemDefault());
LocalDateTime now = LocalDateTime.now(minuteTickingClock);
LocalDateTime roundCeiling = now.plusMinutes(1);
This clock will automatically truncate minutes to floor (although it is specified such that it may return a delayed cached value). Note that a Clock
may be stored in a static variable if desired.
Finally, if this is a common operation that you want to use in multiple places, it is possible to write a library TemporalAdjuster
function to perform the rounding. (Adjusters can be written once, tested, and made available as a static variable or method).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…