We all know that the new Joda date-handling API has been used since JDK 8.

In this API, two new classes, Period and Duration, have been added to calculate the interval between two dates.

Use Period if you don’t need a second or nanosecond level comparison. Period is a coarser type of comparison, usually accurate to Days, Months, and Years.

Duration is a nanosecond comparison that is usually very precise and does not lose precision, while Period may lose precision.

Thread safety and variability

Both classes are:

  • Thread-Safe
  • Immutable

Contrast and difference

The comparison accuracy of the two classes is not different.

Duration contains seconds, nanoseconds. Period Returns only the number of years, months, and days. Duration Returns the number of days, hours, minutes, and milliseconds.

The two classes can use different types. A Period can only use LocalDate, in other words, a Period can only use Date objects.

Duration can use Instant objects.

For example:

Instant t1, t2; . long ns = Duration.between(t1, t2).toNanos();Copy the code

The nanosecond difference between the two times will be calculated.

Consider the following code for calculating birthdays:

Period p = Period.between(birthday, today);
        long p2 = ChronoUnit.DAYS.between(birthday, today);
        System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
                " months, and " + p.getDays() +
                " days old. (" + p2 + " days total)");
Copy the code

The code will print:

You are 41 years, 8 months, and 0 days old. (15219 days total)

Because we do not need very high precision in the calculation of birthdays and dates, so is the above code very convenient?

No more suffering from the old Java date API.

www.ossez.com/t/jdk-8-jdk…