当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Instant query()用法及代码示例


Instant类的query()方法,用于使用指定的查询作为参数来查询此瞬间。作为参数传递的TemporalQuery对象定义了用于从该瞬间获取结果的逻辑。

用法:

public <R> R query(TemporalQuery<R> query)

参数:此方法仅接受一个要调用的参数查询。


返回值:此方法返回查询结果,可能返回null。

异常:此方法引发以下异常:

  • DateTimeException–如果无法查询。
  • ArithmeticException–如果发生数字溢出。

以下示例程序旨在说明query()方法:

示例1:

// Java program to demonstrate 
// Instant.query() method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create Instant object 
        Instant instant 
            = Instant.parse("2018-12-31T10:15:30.00Z"); 
  
        // apply query method of Instant class 
        String value 
            = instant.query(TemporalQueries.precision()) 
                  .toString(); 
  
        // print the result 
        System.out.println("Precision value for Instant is "
                           + value); 
    } 
}
输出:
Precision value for Instant is Nanos

示例2:显示如果查询未找到所需的对象,则返回null。

// Java program to demonstrate 
// Instant.query() method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create Instant object 
        Instant instant 
            = Instant.parse("2018-12-31T10:15:30.00Z"); 
  
        // apply query method of Instant class 
        // print the result 
        System.out.println("Zone value for Instant is "
                           + instant.query(TemporalQueries.offset())); 
    } 
}
输出:
Zone value for Instant is null

参考:
https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#query(java.time.temporal.TemporalQuery)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 Instant query() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。