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

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

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

ChronoLocalDateTime类的toEpochSecond()方法用于将此 ChronoLocalDateTime 转换为自 1970-01-01T00:00:00Z 纪元以来的秒数。该方法将此 ChronoLocalDateTime 与作为参数传递的偏移量相结合,以计算纪元秒值,即从 1970-01-01T00:00:00Z 开始经过的秒数。纪元之后时间线上的瞬间是正的,更早的是负的。

句法:

default long toEpochSecond(ZoneOffset offset)

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

返回值:此方法返回long ,即自1970-01-01T00:00:00Z epoch 以来的秒数,可能为负数。

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

方案一:

// Java program to demonstrate
// ChronoLocalDateTime.toEpochSecond() 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("Epoch Second: "
                           + time.toEpochSecond(zone));
    }
}
输出:
ChronoLocalDateTime: 2019-12-31T19:15:30
Passed ZoneOffset: Z
Epoch Second: 1577819730

方案二:

// Java program to demonstrate
// ChronoLocalDateTime.toEpochSecond() 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("Epoch Second: "
                           + time.toEpochSecond(zone));
    }
}
输出:
ChronoLocalDateTime: 2018-10-25T23:12:31.123
Passed ZoneOffset: Z
Epoch Second: 1540509151

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