[threeten-dev] Period javadoc

Yann Le Tallec ylt at letallec.org
Wed Jan 15 14:42:42 PST 2014


Hi all,
​​
I have used java.time in a project recently and three persons in the
project made the same mistake: calling Period#getDays() to retrieve the
total number of days in a Period. Everybody had read the javadoc but still
produced code such as:

    LocalDate d1 = ...
    LocalDate d2 = ...
    int daysBetweenD1andD2 = Period.between(d1, d2).getDays(); //instead of
DAYS.between(d1, d2);

It seems the confusion came from the javadoc for the getDays method: "Gets
the amount of days of this period."

I don't know if it's too late for javadoc changes but I would suggest that
it should be made clearer that `getDays` returns the day component of the
period excluding the month and year components and is therefore different
from the total number of days that the period represents (which is a vague
concept since a Period does not have a start date). It may also be a good
idea to also link to ChronoUnit#between for the use case described above.

--------

Suggested wording for the class javadoc (this surely can be improved):

This class models a quantity or amount of time in terms of years, months
and days. See Duration<http://download.java.net/jdk8/docs/api/java/time/Duration.html>for
the time-based equivalent to this class. Because a Period does not
have
a start date, its month and year components can't be translated into a
number of days. To calculate the number of days elapsed between two dates,
the ChronoUnit.DAYS#between method should be used.

---------

The javadocs for getYear and getMonth already hint what the behaviour is,
but could maybe made clearer. For example getMonths states: "This means
that a period of "15 months" is different to a period of "1 year and 3
months""
It may be worth adding: "and getMonths() will return 15 and 3 respectively."

Similarly, the following wording could be added to the javadoc of getDays:

The days unit is not automatically normalized with the months and years
unit. This means that a period of "45 days" is different to a period of "1
month and 15 days" and getDays() will return 45 and 15 respectively.

Best,
Yann


More information about the threeten-dev mailing list