LocalTime truncatedTo() method in Java with Examples
Last Updated :
06 Dec, 2018
The truncatedTo() method of a LocalTime class is used to get the value of this LocalTime in the specified unit. This method takes a parameter Unit, which is the unit in which this LocalTime is to be truncated to. It returns a truncated immutable LocalTime with the value in the specified unit.
Syntax:
public LocalTime truncatedTo(TemporalUnit unit)
Parameters: This method accepts a single parameter unit which represents the unit to truncate to, It should not be null.
Return value: This method returns a immutable truncated LocalTime based on this time with the time truncated, not null.
Exception: This method throws following two exception:
- DateTimeException: if unable to truncate.
- UnsupportedTemporalTypeException: if the unit is not supported
Below programs illustrate the truncatedTo() method:
Program 1:
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
LocalTime time
= LocalTime.parse( "21:45:36.13" );
System.out.println( "LocalTime before"
+ " truncate: "
+ time);
LocalTime returnvalue
= time.truncatedTo(ChronoUnit.MINUTES);
System.out.println( "LocalTime after "
+ " truncate: "
+ returnvalue);
}
}
|
Output:
LocalTime before truncate: 21:45:36.130
LocalTime after truncate: 21:45
Program 2:
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
LocalTime time
= LocalTime.parse( "01:21:30.13" );
System.out.println( "LocalTime before"
+ " truncate: "
+ time);
LocalTime returnvalue
= time.truncatedTo(ChronoUnit.HOURS);
System.out.println( "LocalTime after "
+ " truncate: "
+ returnvalue);
}
}
|
Output:
LocalTime before truncate: 01:21:30.130
LocalTime after truncate: 01:00
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#truncatedTo(java.time.temporal.TemporalUnit)
Share your thoughts in the comments
Please Login to comment...