Instant toString() method in Java



The range of values for a field can be obtained using the range() method in the Instant class in Java. This method requires a single parameter i.e. the ChronoField for which the range of values are required and it returns the range of valid values for the ChronoField.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.*; import java.time.temporal.ChronoField; import java.time.temporal.ValueRange; public class Demo { public static void main(String[] args) { Instant i = Instant.now(); ValueRange range1 = i.range(ChronoField.MILLI_OF_SECOND); ValueRange range2 = i.range(ChronoField.MICRO_OF_SECOND); ValueRange range3 = i.range(ChronoField.NANO_OF_SECOND); System.out.println("The current Instant is: " + i); System.out.println("\nThe Range of MILLI_OF_SECOND is: " + range1); System.out.println("The Range of MICRO_OF_SECOND is: " + range2); System.out.println("The Range of NANO_OF_SECOND is: " + range3); } }

Output

The current Instant is: 2019-02-13T09:09:31.210Z The Range of MILLI_OF_SECOND is: 0 - 999 The Range of MICRO_OF_SECOND is: 0 - 999999 The Range of NANO_OF_SECOND is: 0 - 999999999

Now let us understand the above program.

First, the current instant is displayed. Then the range of MILLI_OF_SECOND, MICRO_OF_SECOND and NANO_OF_SECOND is printed using the range() method. A code snippet that demonstrates this is as follows −

Instant i = Instant.now(); ValueRange range1 = i.range(ChronoField.MILLI_OF_SECOND); ValueRange range2 = i.range(ChronoField.MICRO_OF_SECOND); ValueRange range3 = i.range(ChronoField.NANO_OF_SECOND); System.out.println("The current Instant is: " + i); System.out.println("\nThe Range of MILLI_OF_SECOND is: " + range1); System.out.println("The Range of MICRO_OF_SECOND is: " + range2); System.out.println("The Range of NANO_OF_SECOND is: " + range3);
Updated on: 2019-07-30T22:30:25+05:30

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements