Skip to content
Related Articles

Related Articles

Improve Article

Duration truncatedTo(TemporalUnit) method in Java with Examples

  • Last Updated : 26 Nov, 2018

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

Syntax:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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-




My Personal Notes arrow_drop_up
Recommended Articles
Page :