In java.time.Period class, what are the purposes of withDays(), withMonths(), withYears()

I noticed that the java.time.Period class contains a few instance methods that behave the same as the available static factory methods.

  • .withDays() behaves the same as Period.ofDays()
  • .withMonths() behaves the same as Period.ofMonths()
  • .withYears() behaves the same as Period.ofYears()

These instance methods are confusing in that they create a new Period and return them, but without taking into consideration the state of the Period they are called on.

Period p = Period.ofWeeks(3);
p = p.withDays(2);

It seems logical that this would return a period of 3 weeks, 2 days, but it returns only a period of 2 days. This is the same as if I'd called Period.ofDays(2).

Also, there are five other static factory methods without analogous instance methods.

So, is there a reason that these three instance methods would exist? If so, what's the use case?

Jon Skeet
people
quotationmark

You made an unfortunate choice to test with, basically - "weeks" isn't an independent unit; it's just a shorthand for 7 days. From the docs for ofWeeks:

The resulting period will be day-based, with the amount of days equal to the number of weeks multiplied by 7. The years and months units will be zero.

When you then call withDays, that's effectively "overwriting" the number of days in the result, going from 21 days to 2 days.

So try this instead:

Period p = Period.ofMonths(3);
p = p.withDays(2);

This now will be 3 months and 2 days.

people

See more on this question at Stackoverflow