如何将java.time.LocalDate转换为java.util.Date?
以下代码段演示了如何转换java.time.LocalDate为java.util.Date,反之亦然。在代码片段的第一部分中,我们转换为对象LocalDate,Date然后又转换为LocalDate对象。在第二部分中,我们转换为对象LocalDateTime,Date然后又返回为LocalDateTime对象。
package org.nhooo.example.datetime; import java.time.*; import java.util.Date; public class LocalDateToDate { public static void main(String[] args) { //将java.time.LocalDate转换为java.util.Date并返回 //java.time.LocalDate LocalDate localDate = LocalDate.now(); System.out.println("LocalDate = " + localDate); Date date1 = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); System.out.println("Date = " + date1); localDate = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); System.out.println("LocalDate = " + localDate); System.out.println(); //将java.time.LocalDateTime转换为java.util.Date并返回 //java.time.LocalDateTime LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("LocalDateTime = " + localDateTime); Date date2 = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); System.out.println("Date = " + date2); localDateTime = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); System.out.println("LocalDateTime = " + localDateTime); } }
代码段的结果:
LocalDate = 2017-02-14 Date = Tue Feb 14 00:00:00 WITA 2017 LocalDate = 2017-02-14 LocalDateTime = 2017-02-14T10:34:49.562 Date = Tue Feb 14 10:34:49 WITA 2017 LocalDateTime = 2017-02-14T10:34:49.562