Open In App

Duration truncatedTo(TemporalUnit) method in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

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


Output:

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


Output:

Original duration: PT120H
PT120H

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



Last Updated : 26 Nov, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads