Core Java

OCA Java 8 Preparation : Period

In continuation of this post covering the temporal classes – LocalDate, LocalTime and LocalDateTime, today we’ll be covering the Period class which is also on the OCA Java 8 Exam.

Creating Period instances :

Period class also belongs to java.time package. It represents a date-based amount of time in terms of years, months, and days eg : ‘P2Y4M8D‘ signifies 2 years, 4 months and 8 days.Much like all other temporal classes, it is immutable and hence thread-safe. It also exposes static of() method for instantiating its objects along with some other available options.The values can be positive or negative.

The parse() method accepts strings of the format PnYnMnD or PnW where n represents a number and letters P,Y,M,D,W represents period, year, month, day and week respectively.The letters can exist in lower or upper-case. Each string must start with ‘P’ or ‘p’ and must include at-least one of the four sections – year, month, day or week.

As you know, period values can be negative. The parse() method allows to parse such a value. If you precede the complete argument value with ‘- ‘sign, it will be applied to all the values.

Another noteworthy point is that chaining of methods ofYears(),ofMonths(),ofDays() etc doesn’t produces the required result. Try it out.

Querying Period objects :

Following are some methods exposed by the API for querying purposes. They do exactly what their name suggest so we’ll avoid to discuss about them in much detail.

Period class overrides equals() method from Object class. It is important to remember that this method compares each date-based value individually and they must match for this method to return true.For instance, periods ‘P1Y5M’ is not equal to ‘P17M’ and likewise.

Modifying the Period object :

Period class provides withXXX() methods to return a modified copy of this object (as a new object, of-course, Remember : Period is immutable).

Temporal Arithmetic with Periods :

Below are some temporal arithmetic methods you need to know for OCA Java 8 Exam.

Manipulating LocalDate and LocalDateTime using Period :

LocalDate & LocalDateTime also provides methods plus() and minus() which takes a Period argument and performs the manipulation based on the specified argument.

LocalTime cannot be used along with Period as it doesn’t contains any date-based value.

I know this article is a little too packed, covering a lot of details. But with a little practice, you are all set to answer any question on this topic. Keep on reviewing the concepts till you get it all. I am planning to cover DateTimeFormatter in the next blog post. Stay tuned!

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *