Datetime – dome minutes using java 8

So I was lucky to use Java 8 and the new time API, but I didn't see any rounding function

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

It seems possible, but isn't it?

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")));

Solution

java. The time API does not support rounding, but it supports rounding to floor to achieve the desired behavior (this is not the final maximum)

LocalDateTime Now =  LocalDateTime.Now();
LocalDateTime roundFloor =  Now.truncatedTo(ChronoUnit.MINUTES);
LocalDateTime roundCeiling =  Now.truncatedTo(ChronoUnit.MINUTES).plusMinutes(1);

In addition, there is a facility that can get a clock that can only be ticked in one minute, which may be meaningful:

Clock minuteTickingClock = Clock.tickMinutes(ZoneId.systemDefault());
LocalDateTime Now =  LocalDateTime.Now(minuteTickingClock);
LocalDateTime roundCeiling =  Now.plusMinutes(1);

This clock will automatically truncate the minutes to the floor (although it is specified, so it may return the delayed cache value) Note that the clock can be stored in static variables if necessary

Finally, if this is a common operation to use in multiple places, you can write the library temporaladjuster function to perform rounding (the regulator can be written once, tested, and provided as a static variable or method)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>