Instant range() method in Java with Examples
The range() method of Instant class helps to get the range of valid values for the field passes as a parameter. This method returns ValueRange object which contains the minimum and maximum valid values for a field. This instant is helpful to enhance the accuracy of the returned range. When the field is not supported and method is unable to return range values then an exception is thrown.
Syntax:
public ValueRange range(TemporalField field)
Parameters: This method accepts one parameter field which is the field to get range of values.
Returns: This method returns ValueRange which is the range of valid values for the field, not null.
Exception: This method throws following exceptions:
- DateTimeException: if the range for the field cannot be obtained.
- UnsupportedTemporalTypeException: if the field is not supported.
Below programs illustrate the range() method:
Program 1:
import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ValueRange;
public class GFG {
public static void main(String[] args)
{
Instant instant
= Instant.parse( "2018-10-28T19:34:50.63Z" );
System.out.println( "Instant: "
+ instant);
ValueRange range
= instant.range(ChronoField.MILLI_OF_SECOND);
System.out.println( "Range of MILLI_OF_SECOND: "
+ range);
}
}
|
Program 2:
import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ValueRange;
public class GFG {
public static void main(String[] args)
{
Instant instant
= Instant.parse( "2018-10-28T19:34:50.63Z" );
System.out.println( "Instant: "
+ instant);
ValueRange range
= instant.range(ChronoField.NANO_OF_SECOND);
System.out.println( "Range of NANO_OF_SECOND: "
+ range);
}
}
|
Program 3: To get UnsupportedTemporalTypeException
import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ValueRange;
public class GFG {
public static void main(String[] args)
{
Instant instant
= Instant.parse( "2018-10-28T19:34:50.63Z" );
try {
ValueRange secondvalue
= instant.range(ChronoField.ERA);
}
catch (Exception e) {
System.out.println( "Exception: " + e);
}
}
}
|
References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#range(java.time.temporal.TemporalField)
Last Updated :
28 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...