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

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

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

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

句法:

default long toEpochSecond()

参数:此方法不接受任何参数。

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

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

方案一:

// Java program to demonstrate
// ChronoZonedDateTime.toEpochSecond() method
  
import java.time.*;
import java.time.chrono.*;
import java.time.chrono.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create ChronoZonedDateTime object
        ChronoZonedDateTime time
            = ZonedDateTime
                  .parse(
                      "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
  
        // print ChronoZonedDateTime
        System.out.println("ChronoZonedDateTime: "
                           + time);
  
        // print result
        System.out.println("Epoch Second: "
                           + time.toEpochSecond());
    }
}
输出:
ChronoZonedDateTime: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
Epoch Second: 1544104272

方案二:

// Java program to demonstrate
// ChronoZonedDateTime.toEpochSecond() method
  
import java.time.*;
import java.time.chrono.*;
import java.time.chrono.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create ChronoZonedDateTime object
        ChronoZonedDateTime time
            = ZonedDateTime.parse(
                "1918-10-25T23:12:38.543+02:00[Europe/Paris]");
  
        // print ChronoZonedDateTime
        System.out.println("ChronoZonedDateTime: "
                           + time);
  
        // print result
        System.out.println("Epoch Second: "
                           + time.toEpochSecond());
    }
}
输出:
ChronoZonedDateTime: 1918-10-25T23:12:38.543Z[Europe/Paris]
Epoch Second: -1615250842

参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/chrono/ChronoZonedDateTime.html#toEpochSecond–