Java中的 LocalDate toEpochSecond() 方法及示例
LocalDate类的toEpochSecond()方法用于将此 LocalDate 转换为自 1970-01-01T00:00:00Z 纪元以来的秒数。该方法将此本地日期与作为参数传递的指定时间和偏移量相结合,以计算纪元秒值,即从 1970-01-01T00:00:00Z 开始经过的秒数。纪元之后时间线上的瞬间是正的,更早的是负的。
句法:
public long toEpochSecond(LocalTime time,
ZoneOffset offset)
参数:该方法接受两个参数时间和偏移量,分别是本地时间和区域偏移量。
返回值:此方法返回long ,即自1970-01-01T00:00:00Z epoch 以来的秒数,可能为负数。
下面的程序说明了 toEpochSecond() 方法:
方案一:
// Java program to demonstrate
// LocalDate.toEpochSecond() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create a LocalDate object
LocalDate localD
= LocalDate.parse("2018-12-06");
// print LocalDate
System.out.println("LocalDate: "
+ localD);
// create a LocalTime object
LocalTime time
= LocalTime.parse("20:12:32");
// print Instant
System.out.println("Passed LocalTime: "
+ time);
// create ZoneId
ZoneOffset zone = ZoneOffset.of("Z");
// print ZoneId
System.out.println("Passed ZoneOffset: "
+ zone);
// print result
System.out.println("Epoch Second: "
+ localD.toEpochSecond(time, zone));
}
}
输出:
LocalDate: 2018-12-06
Passed LocalTime: 20:12:32
Passed ZoneOffset: Z
Epoch Second: 1544127152
方案二:
// Java program to demonstrate
// LocalDate.toEpochSecond() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create a LocalDate object
LocalDate localD
= LocalDate.parse("2019-01-01");
// print LocalDate
System.out.println("LocalDate: "
+ localD);
// create a LocalTime object
LocalTime time
= LocalTime.parse("00:00:00");
// print Instant
System.out.println("Passed LocalTime: "
+ time);
// create ZoneId
ZoneOffset zone = ZoneOffset.of("Z");
// print ZoneId
System.out.println("Passed ZoneOffset: "
+ zone);
// print result
System.out.println("Epoch Second: "
+ localD.toEpochSecond(time, zone));
}
}
输出:
LocalDate: 2019-01-01
Passed LocalTime: 00:00
Passed ZoneOffset: Z
Epoch Second: 1546300800
参考: https://docs.oracle.com/javase/10/docs/api/java Java .time.LocalTime, Java Java)