Java8 日期时间API,新增了LocalDate、LocalDateTime、LocalTime等线程安全类,接下来要说的是LocalDate与java.util.Date之间的转换。
1、LocalDate不包含时间,描述的是日期,如果对时间不关心,可以使用LocalDate
2、Date转LocalDate
- public static void main(String[] args) {
- Date date = new Date();
- LocalDate localDate = LocalDate.now();
- LocalDateTime localDateTime = LocalDateTime.now();
- System.out.println("date2LocalDate:"+date2LocalDate(date));
- }
-
- /**
- * Date转LocalDate
- * @param date
- */
- public static LocalDate date2LocalDate(Date date) {
- if(null == date) {
- return null;
- }
- return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
- }
控制台输出:
date2LocalDate:2018-06-28
3、LocalDate转Date
- public static void main(String[] args) {
- Date date = new Date();
- LocalDate localDate = LocalDate.now();
- LocalDateTime localDateTime = LocalDateTime.now();
- System.out.println("localDate2Date:"+localDate2Date(localDate));
- }
- /**
- * LocalDate转Date
- * @param localDate
- * @return
- */
- public static Date localDate2Date(LocalDate localDate) {
- if(null == localDate) {
- return null;
- }
- ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
- return Date.from(zonedDateTime.toInstant());
- }
控制台输出:localDate2Date:Thu Jun 28 00:00:00 CST 2018