将Instant转换为Java LocalDateTime,LocalTime
时间:2020-01-09 10:35:42 来源:igfitidea点击:
在这篇文章中,我们将看到Java程序将java.time.Instant转换为LocalDate,LocalTime和LocalDateTime。
1.即时消息提供UTC(世界标准时间)的即时时间点,因此将其转换为LocalDate,LocalDateTime涉及将即时数据转换为
- 通过指定使用的ZoneID来设置ZonedDateTime。
- 通过指定使用的ZoneOffset来设置OffsetDateTime。
一旦有了ZonedDateTime或者OffsetDateTime的实例,就可以分别使用方法toLocalDate(),toLocalTime()和toLocalDateTime()来获取LocalDate,LocalTime或者LocalDateTime。
2.另一种方法是在LocalDate,LocalTime,LocalDateTime类中使用ofInstant()静态方法进行转换。
使用ZonedDateTime即时到LocalDate,LocalDateTime
public class InsantExample { public static void main(String[] args) { Instant instant = Instant.parse("2019-10-20T02:35:15.245Z"); System.out.println("Instant- " + instant); // Getting ZonedDateTime ZonedDateTime zdt = instant.atZone(ZoneId.of("Europe/Paris")); System.out.println("ZonedDateTime- " + zdt); // Getting LocalDate System.out.println("LocalDate- " + zdt.toLocalDate()); System.out.println("LocalTime- " + zdt.toLocalTime()); System.out.println("LocalDateTime- " + zdt.toLocalDateTime()); } }
输出:
Instant- 2019-10-20T02:35:15.245Z ZonedDateTime- 2019-10-20T04:35:15.245+02:00[Europe/Paris] LocalDate- 2019-10-20 LocalTime- 04:35:15.245 LocalDateTime- 2019-10-20T04:35:15.245
使用OffsetDateTime即时到LocalTime,LocalDateTime
public class InsantExample { public static void main(String[] args) { Instant instant = Instant.parse("2019-10-20T02:35:15.245Z"); System.out.println("Instant- " + instant); // Getting OffsetDateTime by specifying offset OffsetDateTime odt = instant.atOffset(ZoneOffset.of("+02:00")); System.out.println("OffsetDateTime- " + odt); // Getting LocalDate System.out.println("LocalDate- " + odt.toLocalDate()); System.out.println("LocalTime- " + odt.toLocalTime()); System.out.println("LocalDateTime- " + odt.toLocalDateTime()); } }
输出:
Instant- 2019-10-20T02:35:15.245Z OffsetDateTime- 2019-10-20T04:35:15.245+02:00 LocalDate- 2019-10-20 LocalTime- 04:35:15.245 LocalDateTime- 2019-10-20T04:35:15.245
使用ofInstant()方法
对于LocalDate
Instant instant = Instant.parse("2019-10-20T02:35:15.245Z"); System.out.println("Instant- " + instant); LocalDate ld = LocalDate.ofInstant(instant, ZoneId.of("Asia/Kolkata")); System.out.println("LocalDate- " + ld);
输出:
Instant- 2019-10-20T02:35:15.245Z LocalDate- 2019-10-20
对于本地时间
Instant instant = Instant.parse("2019-10-20T02:35:15.245Z"); System.out.println("Instant- " + instant); LocalTime lt = LocalTime.ofInstant(instant, ZoneId.of("Asia/Kolkata")); System.out.println("LocalTime- " + lt);
输出:
Instant- 2019-10-20T02:35:15.245Z LocalTime- 08:05:15.245
对于LocalDateTime
Instant instant = Instant.parse("2019-10-20T02:35:15.245Z"); System.out.println("Instant- " + instant); LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata")); System.out.println("LocalDateTime- " + ldt);
输出:
Instant- 2019-10-20T02:35:15.245Z LocalDateTime- 2019-10-20T08:05:15.245