Java ChronoLocalDateTime toEpochSecond()方法及实例
ChronoLocalDateTime 类的 toEpochSecond() 方法用于将此ChronoLocalDateTime转换为自1970-01-01T00:00:00Z这个纪元以来的秒数。该方法将ChronoLocalDateTime与作为参数传递的偏移量结合起来,计算出纪元秒值,即从1970-01-01T00:00:00Z开始的已过秒数。时间轴上的纪元后的时刻为正,较早的为负。
语法
default long toEpochSecond(ZoneOffset offset)
参数: 该方法接受一个参数 offset ,即区域偏移。
返回值: 该方法返回 long ,即从1970-01-01T00:00:00Z开始的秒数,可能为负数。
以下程序说明了toEpochSecond()方法。
程序1 :
// 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
程序2
// 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-