📌  相关文章
📜  Java中的 ChronoLocalDateTime toInstant() 方法及示例

📅  最后修改于: 2022-05-13 01:54:18.794000             🧑  作者: Mango

Java中的 ChronoLocalDateTime toInstant() 方法及示例

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

句法:

default Instant toInstant(ZoneOffset offset)

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

返回值:此方法返回Instant ,即此 ChronoLocalDateTime 的 Instant

下面的程序说明了 toInstant() 方法:

方案一:

// 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

方案二:

// 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-