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


Java ChronoLocalDateTime toInstant()用法及代码示例


ChronoLocalDateTime类的toInstant()方法用于将此ChronoLocalDateTime转换为Instant。该方法将此ChronoLocalDateTime与作为参数传递的偏移量结合起来以计算Instant。

用法:

default Instant toInstant(ZoneOffset offset)

参数:此方法接受参数offset,即区域偏移。


返回值:此方法返回Instant,这是此ChronoLocalDateTime的Instant。

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

示例1:

// Java program to demonstrate 
// ChronoLocalDateTime.toInstant() method 
  
import java.time.*; 
import java.time.chrono.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create ChronoLocalDateTime object 
        ChronoLocalDateTime time 
            = LocalDateTime 
                  .parse("2019-12-31T19:15:30"); 
  
        // print ChronoLocalDateTime 
        System.out.println("ChronoLocalDateTime: "
                           + time); 
  
        // create ZoneId 
        ZoneOffset zone = ZoneOffset.of("Z"); 
  
        // print ZoneId 
        System.out.println("Passed ZoneOffset: "
                           + zone); 
  
        // print result 
        System.out.println("Instant: "
                           + time.toInstant(zone)); 
    } 
}
输出:
ChronoLocalDateTime: 2019-12-31T19:15:30
Passed ZoneOffset: Z
Instant: 2019-12-31T19:15:30Z

示例2:

// Java program to demonstrate 
// ChronoLocalDateTime.toInstant() method 
  
import java.time.*; 
import java.time.chrono.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create ChronoLocalDateTime object 
        ChronoLocalDateTime time 
            = LocalDateTime.parse( 
                "2018-10-25T23:12:31.123"); 
  
        // print ChronoLocalDateTime 
        System.out.println("ChronoLocalDateTime: "
                           + time); 
  
        // create ZoneId 
        ZoneOffset zone = ZoneOffset.of("Z"); 
  
        // print ZoneId 
        System.out.println("Passed ZoneOffset: "
                           + zone); 
  
        // print result 
        System.out.println("Instant: "
                           + time.toInstant(zone)); 
    } 
}
输出:
ChronoLocalDateTime: 2018-10-25T23:12:31.123
Passed ZoneOffset: Z
Instant: 2018-10-25T23:12:31.123Z

参考: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDateTime.html#toInstant-java.time.ZoneOffset-



相关用法


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