将LocalDate,LocalTime,LocalDateTime转换为Java Instant
时间:2020-01-09 10:35:25 来源:igfitidea点击:
在本文中,我们将看到Java程序将LocalDate,LocalTime和LocalDateTime转换为java.time.Instant。
在Java中将LocalDate转换为Instant
即时提供UTC(世界标准时间)的瞬时时间,因此将LocalDate转换为即时需要向LocalDate添加时间。
在LocalDate类中,有一个atStartOfDay(ZoneId zone)方法,该方法根据传递的ZoneId的时区规则,在最早的有效时间从此LocalDate返回ZonedDateTime。
一旦有了ZonedDateTime实例,就可以在该实例上调用toInstant()方法以获取Instant。
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class InsantExample {
public static void main(String[] args) {
LocalDate localDate = LocalDate.parse("2020-07-29");
ZonedDateTime zdt = localDate.atStartOfDay(ZoneId.systemDefault());
System.out.println("Zoned date time- " + zdt);
Instant instant = zdt.toInstant();
System.out.println("Instant- " + instant);
}
}
在Java中将LocalTime转换为Instant
如果我们有LocalTime,则必须先向其添加日期以获取LocalDateTime,然后才能使用LocalTime的atDate()方法。
通过将时区信息添加到LocalDateTime,我们可以获取ZonedDateTime,然后将其转换为Instant。
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
public class InsantExample {
public static void main(String[] args) {
LocalTime time = LocalTime.of(10, 53);
LocalDateTime ldt = time.atDate(LocalDate.parse("2020-07-29"));
Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();
System.out.println("Instant- " + instant);
}
}
在Java中将LocalDateTime转换为Instant
LocalDateTime同时具有日期和时间信息,为了将LocalDateTime转换为Instant,我们只需要添加时区信息。这可以通过以下方式来完成。
将ZoneId添加到LocalDateTime并将其隐蔽到ZonedDateTime。
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
System.out.println("Instant- " + zdt.toInstant());
通过使用toInstant(ZoneOffset offset)方法-
LocalDateTime ldt = LocalDateTime.now();
ZoneId zone = ZoneId.of("Asia/Kolkata");
System.out.println("Instant- " + ldt.toInstant(zone.getRules().getOffset(ldt)));
在Java中将ZonedDateTime转换为Instant
由于ZonedDateTime具有所有信息;日期,时间和时区仅使用toInstant()方法将ZonedDateTime转换为Instant。
ZonedDateTime zdt = ZonedDateTime.now();
System.out.println("Instant- " + zdt.toInstant());

