Java8 Date与LocalDate互转

Java8 日期时间API,新增了LocalDate、LocalDateTime、LocalTime等线程安全类,接下来要说的是LocalDate与java.util.Date之间的转换。

1、LocalDate不包含时间,描述的是日期,如果对时间不关心,可以使用LocalDate

2、Date转LocalDate

  1.     public static void main(String[] args) {
  2. Date date = new Date();
  3. LocalDate localDate = LocalDate.now();
  4. LocalDateTime localDateTime = LocalDateTime.now();
  5. System.out.println("date2LocalDate:"+date2LocalDate(date));
  6. }
  7. /**
  8. * Date转LocalDate
  9. * @param date
  10. */
  11. public static LocalDate date2LocalDate(Date date) {
  12. if(null == date) {
  13. return null;
  14. }
  15. return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
  16. }

控制台输出:

date2LocalDate:2018-06-28

3、LocalDate转Date

  1.     public static void main(String[] args) {
  2. Date date = new Date();
  3. LocalDate localDate = LocalDate.now();
  4. LocalDateTime localDateTime = LocalDateTime.now();
  5. System.out.println("localDate2Date:"+localDate2Date(localDate));
  6. }
  7.     /**
  8. * LocalDate转Date
  9. * @param localDate
  10. * @return
  11. */
  12. public static Date localDate2Date(LocalDate localDate) {
  13. if(null == localDate) {
  14. return null;
  15. }
  16. ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
  17. return Date.from(zonedDateTime.toInstant());
  18. }
控制台输出:
localDate2Date:Thu Jun 28 00:00:00 CST 2018




原文地址:https://blog.csdn.net/chunzhilianxue/article/details/80847610
posted @ 2019-07-05 13:14  星朝  阅读(45304)  评论(1编辑  收藏  举报