Java 中的 Instant range()方法


在 Java 中,可以使用 Instant 类中的 range() 方法获取字段的值域。此方法需要一个参数,即需要获取值域的 ChronoField,并返回 ChronoField 的有效值域。

演示此方法的程序如下所示-

示例

 在线演示

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("
The 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); } }

输出

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

现在让我们了解一下上述程序。

首先显示当前瞬间。然后使用 range() 方法打印 MILLI_OF_SECOND、MICRO_OF_SECOND 和 NANO_OF_SECOND 的值域。演示此方法的代码片段如下所示-

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("
The 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);

更新于:2019-07-30

634 次浏览

启动你的 职业生涯

完成课程认证

开始学习
广告