java.time
LocalDate 只包含日期
LocalTime 只包含时间
LocalDateTime 包含日期和时间
相互转换
-
LocalDate/LocalDateTime转Date
Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()); Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
-
LocalDate/LocalDateTime转字符串
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyy-MM-dd"));
-
Date转LocalDate和LocalDateTime
LocalDateTime.ofInstant(new Date().toInstant()); LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()).toLocalDate();
-
字符串转LocalDate和LocalDateTime
LocalDateTime.parse("2019-09-01 00:01:02", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); LocalDate.parse("2019-09-01");
时间比较
isAfter/isBefore
时间间隔
//基于日期时间数量的间隔,比如 1天/2周/3年
Period.between(LocalDate.now(), LocalDate.now().plusDays(3)).getDays();
//基于精确时间的间隔,比如1秒/1000纳秒
Duration.between(LocalDateTime.now(),LocalDateTime.now().plusMinutes(2)).getSeconds(); // 120
Duration.between(LocalDateTime.now(),LocalDateTime.now(ZoneId.of("Europe/London"))).getSeconds()); //-25200
Duration.between(LocalDateTime.now(),LocalDateTime.now(ZoneId.of("Europe/London"))).toHours()); //01