When capturing elapsed time as a Duration, I only care about whole seconds resolution.
How do I drop the fractional second from a Duration object?
Other classes in the java.time framework offer a truncatedTo method. But I do not see one on Duration.
Java 9 brought some minor features and bug fixes to the java.time classes that debuted in Java 8.
One of those features is adding a Duration::truncatedTo method, similar to such methods seen on other classes. Pass a ChronoUnit (an implementation of TemporalUnit interface) to specify the granularity of what to truncate.
Duration d = myDuration.truncatedTo( ChronoUnit.SECONDS ) ;
If you are using Java 8 and cannot yet move to Java 9, 10, 11, or later, then calculate the truncation yourself.
Call the minusNanos method found on the Java 8 version of Duration. Get the number of nanoseconds on the Duration object, then subtract that number of nanoseconds.
Duration d = myDuration.minusNanos( myDuration.getNano() ) ;
The java.time classes use the immutable objects pattern. So you get back a fresh new object without altering (“mutating”) the original.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With