5/27/2020

Duration vs Period in Java 8

Both classes can be used to represent an amount of time or also measure the difference two dates.
How to use both in different situations?

  • date-based value (Period): check whether days of period is over setting.

    LocalDate localDate = java.time.LocalDate.parse(matcher.group(1), DATE_TIME_FORMATTER);
    long days = Period.between(localDate, java.time.LocalDate.now()).getDays();
    return (days >= 5);
  • time-based value (Duration): check an interval of time in seconds or nanoseconds.

    Duration.between(startTime, LocalTime.now()).getSeconds();

Ref

Java Period and Duration

No comments:

Post a Comment