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:
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:
import java.time.Duration;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
Duration duration
= Duration.parse( "P2DT3H4M" );
System.out.println( "Original duration: "
+ duration);
System.out.println(
duration
.truncatedTo(ChronoUnit.SECONDS));
}
}
|
Output:
Original duration: PT51H4M
PT51H4M
Example 2:
import java.time.Duration;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
Duration duration
= Duration.ofDays( 5 );
System.out.println( "Original duration: "
+ duration);
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-
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...