Java8如何实现LocalDate和ZonedDateTime相互转换

后端 潘老师 6个月前 (10-31) 206 ℃ (0) 扫码查看

在Java 8中,学习如何将LocalDate转换为ZonedDateTime,以及将ZonedDateTime转换为LocalDate。

我们知道,LocalDate表示没有时间和时区信息的日期。ZonedDateTime实例包含所有三个信息,即日期、时间和时区。

ZonedDateTime = LocalDate + 时间 + 时区

1.LocalDate如何转为ZonedDateTime

要将LocalDate实例转换为ZonedDateTime实例,有两种方法。

1.1 LocalDate -> ZonedDateTime

如果我们只想将当前时区的本地日期转换为不同时区的本地日期,即只想添加时区信息,那么我们可以使用LocalDate.atStartOfDay(zoneId)方法。

LocalDate localDate = LocalDate.now();
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.of("EST5EDT"));
System.out.println(zonedDateTime);//2019-04-02T00:00-04:00[EST5EDT]

1.2 LocalDate -> LocalDateTime -> ZonedDateTime

如果我们想同时添加时间和时区信息到本地日期,那么我们需要分别添加这两部分以获得ZonedDateTime实例。我们可以使用以下方法向本地日期添加时间信息。

  • ZonedDateTime atStartOfDay()
  • ZonedDateTime atTime(LocalTime time)
  • ZonedDateTime atTime(int hour, int minutes)
  • ZonedDateTime atTime(int hour, int minutes, int seconds)
  • ZonedDateTime atTime(int hour, int minute, int second, int nanoOfSecond)

然后,我们可以使用LocalDateTime.atZone(ZoneId)方法添加时区信息。

LocalDate localDate = LocalDate.now();  //本地日期
LocalDateTime localDateTime = localDate.atTime(10, 45, 56);  //添加时间信息
ZoneId zoneId = ZoneId.of("Asia/Kolkata"); // Zone information
ZonedDateTime zdtAtAsia = localDateTime.atZone(zoneId); // 添加时区信息
ZonedDateTime zdtAtET = zdtAtAsia
        .withZoneSameInstant(ZoneId.of("America/New_York")); // 与欧洲东部时间同步
System.out.println(zdtAtAsia);
System.out.println(zdtAtET);

程序输出。

2019-04-02T10:45:56+05:30[Asia/Kolkata]
2019-04-02T01:15:56-04:00[America/New_York]

2. ZonedDateTime如何转为LocalDate

要将ZonedDateTime转换为LocalDate实例,请使用toLocalDate()方法。它返回与给定日期时间相同的年份、月份和日期的LocalDate。

ZonedDateTime zonedDateTime = ZonedDateTime.now();
LocalDate localDate = zonedDateTime.toLocalDate();
System.out.println(localDate);//2019-04-02

以上就是Java8如何实现LocalDate和ZonedDateTime相互转换的全部的内容。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/back/10528.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】