Round minutes to ceiling using Java 8

谁都会走 提交于 2019-11-28 21:08:01

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).

LocalDateTime newTime = now.plusMinutes(1).minusNanos(1).withSecond(0).withNano(0);

This will round up to the nearest minute, acting as a ceiling function with minutes as the integer part.

java.time (the new time API in Java 8) has no rounding features like some other libraries. You try to use formatting to round on String-level. If you want to round the time objects however, then you can do this rounding manually:

LocalDateTime now =  LocalDateTime.now(Clock.systemUTC());
LocalDateTime newTime =  now.plusMinutes(1).withSecond(0).withNano(0);

By the way, you surely meant floor, not ceiling, isn't it?

Update:

I have found this slightly better way for setting to floor (obviously the only rounding feature, ceiling is not supported):

LocalDateTime now =  LocalDateTime.now(Clock.systemUTC());
LocalDateTime newTime =  now.plusMinutes(1).truncatedTo(ChronoUnit.MINUTES);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!