Duration truncatedTo(TemporalUnit) method in Java with Examples

The truncatedTo(Temporal) method of Duration Class in java.time package is used get the value of this duration in the specified unit.

Syntax:

public Duration truncatedTo(TemporalUnit unit)

Parameters: This method accepts a parameter unit which is the unit to which this duration value is to be converted to.



Return Value: This method returns a duration with the value truncated to the specified unit.

Exception: This method throws:

  • DateTimeException: if the unit is invalid.
  • UnsupportedTemporalTypeException: if the unit is not supported.

Below examples illustrate the Duration.truncatedTo() method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate truncatedTo() method
  
import java.time.Duration;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Duration using parse() method
        Duration duration
            = Duration.parse("P2DT3H4M");
  
        System.out.println("Original duration: "
                           + duration);
  
        // Truncate the duration to seconds
        // using truncatedTo() method
        System.out.println(
            duration
                .truncatedTo(ChronoUnit.SECONDS));
    }
}

chevron_right


Output:

Original duration: PT51H4M
PT51H4M

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate truncatedTo() method
  
import java.time.Duration;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Duration
        Duration duration
            = Duration.ofDays(5);
  
        System.out.println("Original duration: "
                           + duration);
  
        // Truncate the duration to nano-seconds
        // using truncatedTo() method
        System.out.println(
            duration
                .truncatedTo(ChronoUnit.NANOS));
    }
}

chevron_right


Output:

Original duration: PT120H
PT120H

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#truncatedTo-java.time.temporal.TemporalUnit-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.