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:
// Java program to demonstrate // Instant.range() method import java.time.*; import java.time.temporal.ChronoField; import java.time.temporal.ValueRange; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse( "2018-10-28T19:34:50.63Z" ); // print Instant System.out.println( "Instant: " + instant); // get range of MILLI_OF_SECOND field // from instant using range method ValueRange range = instant.range(ChronoField.MILLI_OF_SECOND); // print range of MILLI_OF_SECOND System.out.println( "Range of MILLI_OF_SECOND: " + range); } } |
Program 2:
// Java program to demonstrate // Instant.range() method import java.time.*; import java.time.temporal.ChronoField; import java.time.temporal.ValueRange; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse( "2018-10-28T19:34:50.63Z" ); // print Instant System.out.println( "Instant: " + instant); // get range of NANO_OF_SECOND field // from instant using range method ValueRange range = instant.range(ChronoField.NANO_OF_SECOND); // print range of NANO_OF_SECOND System.out.println( "Range of NANO_OF_SECOND: " + range); } } |
Program 3: To get UnsupportedTemporalTypeException
// Java program to demonstrate // Instant.range() method import java.time.*; import java.time.temporal.ChronoField; import java.time.temporal.ValueRange; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse( "2018-10-28T19:34:50.63Z" ); // try to find range of era using ChronoField try { ValueRange secondvalue = instant.range(ChronoField.ERA); } catch (Exception e) { // print exception System.out.println( "Exception: " + e); } } } |
References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#range(java.time.temporal.TemporalField)