当前位置: 代码迷 >> 综合 >> JDK8时间处理API:Duration、Period和ChronoUnit
  详细解决方案

JDK8时间处理API:Duration、Period和ChronoUnit

热度:44   发布时间:2023-12-22 19:08:05.0

时间处理

问题来源:处理时间差值
  1. 需求:计算两个YearMonth之间相差月数
    String serialDate=n.getSerialDate();//获取日期字符串形如:202108oldDate = YearMonth.parse(serialDate, "yyyyMM");newDate = YearMonth.now();//返回两个日期间相差日期是否超过六个月
return (nowDate.getYear()-oldDate.getYear())*12+(nowDate.getMonthValue()-oldDate.getMonthValue())>6;
  1. 使用ChronoUnit
	String serialDate=n.getSerialDate();//获取日期字符串形如:202108oldDate = YearMonth.parse(serialDate, "yyyyMM");newDate = YearMonth.now();return ChronoUnit.MONTHS.between(oldMonth, nowMonth) > 6;
  • 扩展
  • Duration

主要用来衡量秒级和纳秒级的时间,使用于时间精度要求比较高的情况。
Duration是一个final class,并且它是可序列化和可比较的。实现了TemporalAmount接口
此接口定义了必须实现的四个方法
long get(TemporalUnit unit);
List getUnits();
//TemporalUnit代表的是时间对象的单位,比如:years, months, days, hours, minutes 和 seconds.
Temporal addTo(Temporal temporal);
Temporal subtractFrom(Temporal temporal);
//Temporal代表的是对时间对象的读写操作

我们可以用他对Instance,LocalTime进行计算

通过of 或between创建Duration对象

 Instant start = Instant.parse("2020-08-03T10:15:30.00Z");Instant end = Instant.parse("2020-08-03T10:16:30.12Z");
// LocalTime start2 = LocalTime.of(1, 20, 25, 1314);
//LocalTime end2 = LocalTime.of(3, 22, 27, 1516);
//Duration.between(start2, end2).getSeconds();
Duration duration = Duration.between(start, end);log.info("{}",duration.getSeconds());log.info("{}",duration.getNano());log.info("{}",duration.getUnits());
  • Period

    Period的单位是year, month 和day 。操作基本上和Duration是一致的。
    他是final Class,实现的ChronoPeriod是TemporalAmount的子接口

我们可以用他对LocalDate进行计算
LocalDate startDate = LocalDate.of(2020, 2, 20);LocalDate endDate = LocalDate.of(2021, 1, 15);Period period = Period.between(startDate, endDate);log.info("{}",period.getDays());log.info("{}",period.getMonths());log.info("{}",period.getYears());
// long l = ChronoPeriod.between(startDate,endDate).get(ChronoUnit.MONTHS);
  • ChronoUnit

ChronoUnit是用来表示时间单位的,但是也提供了一些非常有用的between方法来计算两个时间的差值

        LocalDate startDate = LocalDate.of(2020, 2, 20);LocalDate endDate = LocalDate.of(2021, 1, 15);long years = ChronoUnit.YEARS.between(startDate, endDate);long months = ChronoUnit.MONTHS.between(startDate, endDate);long weeks = ChronoUnit.WEEKS.between(startDate, endDate);long days = ChronoUnit.DAYS.between(startDate, endDate);long hours = ChronoUnit.HOURS.between(startDate, endDate);long minutes = ChronoUnit.MINUTES.between(startDate, endDate);long seconds = ChronoUnit.SECONDS.between(startDate, endDate);long milis = ChronoUnit.MILLIS.between(startDate, endDate);long nano = ChronoUnit.NANOS.between(startDate, endDate);