Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate a Duration in Java

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.

like image 325
Basil Bourque Avatar asked Mar 04 '26 20:03

Basil Bourque


1 Answers

Java 9 and later

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

Java 8

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.

like image 149
Basil Bourque Avatar answered Mar 07 '26 09:03

Basil Bourque