Instant truncatedTo() method in Java with Examples
The truncatedTo() method of an Instant class is used to get the value of this Instant in the specified unit. This method takes a parameter Unit, which is the Unit in which this Instant is to be truncated to. It returns a truncated immutable Instant with the value in the specified unit.
Syntax:
public Instant truncatedTo(TemporalUnit unit)
Parameter: This method takes a parameter unit which is the unit in which this Instant is to be truncated to. It should not be null.
Returns: This method returns an immutable truncated Instant with the value in the specified unit.
Exception: This method throws following Exceptions:
- DateTimeException: if the unit is invalid for truncation.
- UnsupportedTemporalTypeException: if the unit is not supported.
Below programs illustrate the Instant.truncatedTo() method:
Program 1:
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
Instant instant
= Instant.parse( "2018-12-30T09:24:54.63Z" );
System.out.println( "Instant before"
+ " truncate: "
+ instant);
Instant returnvalue
= instant.truncatedTo(ChronoUnit.HOURS);
System.out.println( "Instant after "
+ " truncate: "
+ returnvalue);
}
}
|
Output:
Instant before truncate: 2018-12-30T09:24:54.630Z
Instant after truncate: 2018-12-30T09:00:00Z
Program 2:
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
Instant instant
= Instant.parse( "2018-12-30T09:24:54.63Z" );
System.out.println( "Instant before"
+ " truncate: "
+ instant);
Instant returnvalue
= instant.truncatedTo(ChronoUnit.DAYS);
System.out.println( "Instant after "
+ " truncate: "
+ returnvalue);
}
}
|
Output:
Instant before truncate: 2018-12-30T09:24:54.630Z
Instant after truncate: 2018-12-30T00:00:00Z
Program 3: To show Exception:
import java.time.*;
import java.time.temporal.ChronoUnit;
public class GFG {
public static void main(String[] args)
{
Instant instant
= Instant.parse( "2018-12-30T09:24:54.63Z" );
try {
instant.truncatedTo(ChronoUnit.ERAS);
}
catch (Exception e) {
System.out.println( "Exception: " + e);
}
}
}
|
Output:
Exception:
java.time.temporal.UnsupportedTemporalTypeException:
Unit is too large to be used for truncation
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#truncatedTo(java.time.temporal.TemporalUnit)
Last Updated :
29 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...