Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

datetime - Round minutes to ceiling using Java 8

So I'm lucky enough to use Java 8 and the new time APi but I don't see any rounding functions...

Basically if the time is...

2014-08-28T10:01.00.000 ----> 2014-08-28T10:02.00.000
2014-08-28T10:01.10.123 ----> 2014-08-28T10:02.00.000
2014-08-28T10:01.25.123 ----> 2014-08-28T10:02.00.000
2014-08-28T10:01.49.123 ----> 2014-08-28T10:02.00.000
2014-08-28T10:01.59.999 ----> 2014-08-28T10:02.00.000

This seems to be ok, but is it right?

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

System.out.println(newTime.toString());
System.out.println(newTime.format(DateTimeFormatter.ofPattern("yyyy-dd-MM'T'HH:mm:00.000")));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...