Java中Date与 LocalDateTime ,LocalDate之间的转换

x33g5p2x  于2022-06-06 转载在 Java  
字(1.6k)|赞(0)|评价(0)|浏览(601)

Date与LocalDateTime和LocalDate互相转换思路
Date转LocalDateTime和LocalDate都可以通过Date先转换成Instant然后再转换成LocalDateTime和LocalDate,可以按照下图的方式进行转换。LocalDateTime和LocalDate转换成Date也是以Instant为中介来进行转换的。

1)Date转LocalDate的代码如下:

Date date = new Date();
System.out.println(date);
Instant instant = date.toInstant();
LocalDate ld = instant.atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(ld);

运行结果如下

Sat Jun 04 19:13:15 CST 2022
2022-06-04

2) Date转LocalDateTime,LocalDateTime提供了比LocalDate更直接的方法

Date转LocalDateTime转换代码如下:

Date date = new Date();
System.out.println(date);
//可以去查看可用的ZoneId集合,有500多个
Set<String> availableZoneIds = ZoneOffset.getAvailableZoneIds();
LocalDateTime ldt = LocalDateTime.ofInstant(date.toInstant(),ZoneOffset.UTC);
System.out.println(ldt);
LocalDateTime ldt1 = LocalDateTime.ofInstant(date.toInstant(),ZoneOffset.ofHours(5));
System.out.println(ldt1);
Sat Jun 04 19:40:04 CST 2022
2022-06-04T11:40:04.754
2022-06-04T16:40:04.754

3)LocalDate转Date

LocalDate now = LocalDate.now();
System.out.println(now);
Date date = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
System.out.println(date);
2022-06-04
Sat Jun 04 00:00:00 CST 2022

4)LocalDateTime转换成Date也是一样的

LocalDateTime now = LocalDateTime.now();
System.out.println(now);
Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
System.out.println(date);
2022-06-04T19:41:17.715
Sat Jun 04 19:41:17 CST 2022

5)LocalDateTime转LocalDate

LocalDateTime now = LocalDateTime.now();
LocalDate date = now.toLocalDate();
System.out.println(date);
2022-06-04

6)LocalDate转LocalDateTime

LocalDate now = LocalDate.now();
LocalDateTime ldt = now.atStartOfDay();
System.out.println(ldt);
2022-06-04T00:00

相关文章