java中Date与LocalDate、LocalDate、LocalDateTime互相转化

首页 / 新闻资讯 / 正文

一、Date转化为LocalDate、LocalDate、LocalDateTime

1.第一种转换方法,借助新增类ZoneId、Instant、ZonedDateTime

    public static void date2Local() {         Date date = new Date();         //返回当前系统默认的时区         ZoneId zoneId = ZoneId.systemDefault();          //atZone()方法返回在指定时区,从该Instant生成的ZonedDateTime         ZonedDateTime zonedDateTime = date.toInstant().atZone(zoneId);         LocalDate localDate = zonedDateTime.toLocalDate();         LocalTime localTime = zonedDateTime.toLocalTime();         LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();     }

2.第二种,同样使用ZoneId、Instant,但最后不同

public static void date2Local() {         Date date = new Date();         ZoneId zoneId = ZoneId.systemDefault();         Instant instant = date.toInstant();          LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);         LocalDate localDate = localDateTime.toLocalDate();         LocalTime localTime = localDateTime.toLocalTime();     }

3.第三种拓展,java9中新增了LocalDate、LocalTime的ofInstan()方法,所以第二种也可以写成:

    public static void date2Local() {         Date date = new Date();         ZoneId zoneId = ZoneId.systemDefault();         Instant instant = date.toInstant();          LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);         LocalDate localDate = LocalDate.ofInstant(instant, zoneId);         LocalTime localTime = LocalTime.ofInstant(instant, zoneId);     }

二、LocalDate、LocalDate、LocalDateTime转化Date

1. java.time.LocalDateTime → java.util.Date

    public void LocalDateTimeToDate() {         LocalDateTime localDateTime = LocalDateTime.now();         ZoneId zoneId = ZoneId.systemDefault();         Instant instant = localDateTime.atZone(zoneId).toInstant();         Date date = Date.from(instant);     }

2. java.time.LocalDate → java.util.Date

    public void LocalDateToDate() {         LocalDate localDate = LocalDate.now();         ZoneId zone = ZoneId.systemDefault();         //将此日期与午夜时间组合在一起,以便在此日期开始时创建LocalDateTime,即生成2017-02-03T00:00         Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();         Date date = Date.from(instant);     }

3. java.time.LocalTime → java.util.Date

    public void LocalTimeToDate() {         LocalTime localTime = LocalTime.now();         LocalDate localDate = LocalDate.now();         LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);         ZoneId zone = ZoneId.systemDefault();         Instant instant = localDateTime.atZone(zone).toInstant();         Date date = Date.from(instant);     }

三、LocalDate、LocalDate、LocalDateTime中还有很多对日期,时间的操作方法,可以精细到毫秒,在此就不一一介绍了,具体可参考以下文章:

https://www.cnblogs.com/qingyunfc/p/10236734.html