Java Reference
In-Depth Information
Quiz 12.1: Manipulating a LocalDate
What will the value of the date variable be after the following manipulations?
LocalDate date = LocalDate.of(2014, 3, 18);
date = date.with(ChronoField.MONTH_OF_YEAR, 9);
date = date.plusYears(2).minusDays(10);
date.withYear(2011);
Answer:
2016-09-08
As you've seen, you can manipulate the date both in an absolute way and in a relative way. You
can also concatenate more manipulations in a single statement, because every change will create
a new LocalDate object, and the subsequent invocation will manipulate the object created by the
former one. Finally, the last statement in this code snippet has no observable effect because, as
usual, it creates a new LocalDate instance, but we're not assigning this new value to any
variable.
12.2.1. Working with TemporalAdjusters
All the date manipulations you've seen so far are relatively straightforward. Sometimes, you may
need to perform more advanced operations, such as adjusting a date to the next Sunday, the
next working day, or the last day of the month. In such cases you can pass to an overloaded
version of the with method a TemporalAdjuster that provides a more customizable way to define
the manipulation needed to operate on a specific date. The Date and Time API already provides
many predefined Temporal-Adjusters for the most common use cases. You can access them
using the static factory methods contained in the TemporalAdjusters class, as shown next.
Listing 12.8. Using the predefined TemporalAdjusters
Search WWH ::




Custom Search