当前位置: 代码迷 >> 综合 >> Java8 LocalDate/LocalDateTime常用方法
  详细解决方案

Java8 LocalDate/LocalDateTime常用方法

热度:98   发布时间:2023-10-24 14:10:28.0

简单来说,LocalDate就是不带时分秒(为0)的日期,而LocalDateTime则有时分秒。 
新东西当然就得用,下面是一些常用的方法,做个笔记。

  • 获取当前时间
LocalDate now = LocalDate.now();
LocalDate now = LocalDate.now(ZoneId.systemDefault());
LocalDateTime now = LocalDateTime.now();
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
  • 获取指定日期的时间
LocalDate now = LocalDate.of(2017, 9, 22);
LocalDateTime now = LocalDateTime.of(2017, 9, 22, 15, 40, 00);
  • Date转换为LocalDate/LocalDateTime
Date date = new Date();
LocalDate now = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDateTime nowTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

3

  • LocalDate/LocalDateTime转换为Date
LocalDate now = LocalDate.now(ZoneId.systemDefault());
Date date = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
  • 获取两个LocalDate的相差天数
/*** 如果是 now.until(before, ChronoUnit.DAYS), 返回的结果是负数*/
LocalDate before = LocalDate.of(2017, 9, 22);
LocalDate now = LocalDate.now(ZoneId.systemDefault());
long betweenDays = before.until(now, ChronoUnit.DAYS);

 

  相关解决方案