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:
// 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));    }} |
Original duration: PT51H4M PT51H4M
Example 2:
// 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));    }} |
Original duration: PT120H PT120H
