Java Reference
In-Depth Information
Adjusting Dates
Sometimes you want to adjust a date and time to have a particular characteristic, for example, the first Monday
of the month, the next Tuesday, etc. You can perform adjustments to a date and time using an instance of the
TemporalAdjuster interface. The interface has one method, adjustInto() , that takes a Temporal and returns a
Temporal . The Date-Time API provides several commonly used datetime adjusters. If they do not suit your needs, you
can roll out your own adjusters. I will discuss examples of both.
A TemporalAdjusters class is provided. It consists of all static methods that return different types of predefined
date adjusters. The datetime-related classes contain a with(TemporalAdjuster adjuster) method. You need to
pass the returned object from one of the methods of the TemporalAdjusters class to the with() method. The with()
method will return a copy of the original datetime object by adjusting its components using the logic in the adjuster.
The following snippet of code computes the first Monday after January 1, 2014:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
...
LocalDate ld1 = LocalDate.of(2014, Month.JANUARY, 1);
LocalDate ld2 = ld1.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println(ld1);
System.out.println(ld2);
2014-01-01
2014-01-06
The method names are self-explanatory, as you can see in Table 12-3 .
Table 12-3. List of Some Useful Methods in the TemporalAdjusters Class
Method
Description
next(DayOfWeek dayOfWeek)
Returns an adjuster that adjusts the date to be the first specified day of
week after the date being adjusted.
nextOrSame(DayOfWeek dayOfWeek)
Returns an adjuster that adjusts the date to be the first specified day of
week after the date being adjusted. If the date being adjusted is already on
the specified day of week, it returns the same date.
previous(DayOfWeek dayOfWeek)
Returns an adjuster that adjusts the date to be the first specified day of
week before the date being adjusted.
previousOrSame(DayOfWeek
dayOfWeek)
Returns an adjuster that adjusts the date to be the first specified day of
week before the date being adjusted. If the date being adjusted is already
on the specified day of week, it returns the same date.
firstInMonth(DayOfWeek
dayOfWeek),
lastInMonth(DayOfWeek dayOfWeek)
Each returns an adjuster that adjusts the date to be the first/last
(respectively) specified day of week in the month represented by the date
being adjusted.
( continued )
 
Search WWH ::




Custom Search