Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 746
Doug Hughes Avatar asked May 24 '17 10:05

Doug Hughes


People also ask

What are periods for in Java?

The Period Class in Java class obtains a quantity or amount of time in terms of years, months and days. The time obtained is a date-based amount of time in the ISO-8601 calendar system, such as '4 years, 5 months, and 6 days. The units which are supported for a period are YEARS, MONTHS, and days.

How do you declare a period in Java?

Another way to create a Period object is based on the number of days, months, weeks or years using dedicated methods: Period fromUnits = Period. of(3, 10, 10); Period fromDays = Period. ofDays(50); Period fromMonths = Period.

Which of the following are stored in a period object in Java?

The supported units of a period are YEARS , MONTHS and DAYS . All three fields are always present, but may be set to zero. The ISO-8601 calendar system is the modern civil calendar system used today in most of the world.


1 Answers

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.

like image 52
Jon Skeet Avatar answered Nov 08 '22 15:11

Jon Skeet