Sub topic 15
Date Arithmetic Shortcuts with TemporalAdjusters
Many date questions sound simple but take work to answer by hand. What is the last day of this month? When is next Friday? What date is the fourth Thursday of November? You could work these out with plusDays and a loop. Java gives you a shorter and safer way: TemporalAdjusters.
In this chapter you will learn what an adjuster is, how to use the built-in ones, and how to write your own.
What Is a TemporalAdjuster?
A temporal is any java.time object that holds a date or time, such as LocalDate or ZonedDateTime.
A TemporalAdjuster is a rule that takes a temporal and returns a changed copy. For example, the rule might be "move to the last day of the month."
TemporalAdjusters (with an "s" at the end) is a class full of ready-made rules. You get a rule by calling one of its static methods, such as TemporalAdjusters.lastDayOfMonth().
You apply a rule with the with method:
LocalDate result = date.with(TemporalAdjusters.lastDayOfMonth());Remember that java.time objects are immutable, which means they never change. The with method does not change date. It returns a new LocalDate, so you must keep the result.
A First Example
This program starts from Tuesday, November 5, 2024, and jumps to three common dates.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class Adjusters {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 11, 5); // a Tuesday
System.out.println(date.with(TemporalAdjusters.lastDayOfMonth())); // 2024-11-30
System.out.println(date.with(TemporalAdjusters.next(DayOfWeek.FRIDAY))); // 2024-11-08
System.out.println(date.with(TemporalAdjusters.firstDayOfNextMonth())); // 2024-12-01
}
}None of these lines does any math by hand. You do not need to know how many days November has or how many days lie between Tuesday and Friday. The adjuster works that out.
The Built-In Adjusters
The built-in adjusters fall into two groups. Some move to the start or end of a month or year. Others move to a day of the week.
Month and Year Boundaries
| Method | What it returns | From 2024-11-05 |
|---|---|---|
| `firstDayOfMonth()` | Day 1 of the same month | 2024-11-01 |
| `lastDayOfMonth()` | Last day of the same month | 2024-11-30 |
| `firstDayOfNextMonth()` | Day 1 of the next month | 2024-12-01 |
| `firstDayOfYear()` | January 1 of the same year | 2024-01-01 |
| `lastDayOfYear()` | December 31 of the same year | 2024-12-31 |
| `firstDayOfNextYear()` | January 1 of the next year | 2025-01-01 |
Days of the Week
These methods take a DayOfWeek value, such as DayOfWeek.MONDAY.
| Method | What it returns | From Tue 2024-11-05 |
|---|---|---|
| `next(TUESDAY)` | The next Tuesday, never today | 2024-11-12 |
| `nextOrSame(TUESDAY)` | Today if it is Tuesday, else the next one | 2024-11-05 |
| `previous(MONDAY)` | The last Monday before today | 2024-11-04 |
| `previousOrSame(MONDAY)` | Today if Monday, else the last one | 2024-11-04 |
| `firstInMonth(MONDAY)` | First Monday of the month | 2024-11-04 |
| `lastInMonth(FRIDAY)` | Last Friday of the month | 2024-11-29 |
| `dayOfWeekInMonth(4, THURSDAY)` | Fourth Thursday of the month | 2024-11-28 |
The difference between next and nextOrSame causes many bugs. Choose on purpose. If today is Friday and you ask for "the next Friday," do you want today or a week from now?
Here is a program that runs all of these, so you can check the tables yourself:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class WeekdayAdjusters {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 11, 5); // a Tuesday
System.out.println(date.with(TemporalAdjusters.next(DayOfWeek.TUESDAY))); // 2024-11-12
System.out.println(date.with(TemporalAdjusters.nextOrSame(DayOfWeek.TUESDAY))); // 2024-11-05
System.out.println(date.with(TemporalAdjusters.previous(DayOfWeek.MONDAY))); // 2024-11-04
System.out.println(date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY))); // 2024-11-04
System.out.println(date.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))); // 2024-11-29
// US Thanksgiving: the fourth Thursday in November
LocalDate thanksgiving = date.with(TemporalAdjusters.dayOfWeekInMonth(4, DayOfWeek.THURSDAY));
System.out.println(thanksgiving); // 2024-11-28
}
}Edge Cases to Know
Leap Years Are Handled for You
A leap year is a year with a February 29. lastDayOfMonth() knows which years have one.
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class LeapYear {
public static void main(String[] args) {
System.out.println(LocalDate.of(2024, 2, 10).with(TemporalAdjusters.lastDayOfMonth())); // 2024-02-29
System.out.println(LocalDate.of(2023, 2, 10).with(TemporalAdjusters.lastDayOfMonth())); // 2023-02-28
}
}The Time and Zone Stay the Same
Adjusters change only the date part. If you use one on a LocalDateTime or ZonedDateTime, the time of day and the zone are kept.
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
public class KeepsTime {
public static void main(String[] args) {
LocalDateTime meeting = LocalDateTime.of(2024, 11, 5, 14, 30);
System.out.println(meeting.with(TemporalAdjusters.lastDayOfMonth())); // 2024-11-30T14:30
}
}LocalTime Cannot Use Date Adjusters
A LocalTime has no date, so it cannot move to "the last day of the month." If you try, Java throws an UnsupportedTemporalTypeException while the program runs. The code still compiles, so the mistake shows up only at run time.
Writing Your Own Adjuster
Sometimes no built-in rule fits. A common need is "the next working day," which skips Saturday and Sunday.
TemporalAdjusters.ofDateAdjuster turns a small function into an adjuster. A lambda is a short, unnamed function written with ->. Your lambda gets a LocalDate and returns the new LocalDate.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
public class WorkingDay {
static final TemporalAdjuster NEXT_WORKING_DAY = TemporalAdjusters.ofDateAdjuster(d -> {
LocalDate next = d.plusDays(1);
while (next.getDayOfWeek() == DayOfWeek.SATURDAY
|| next.getDayOfWeek() == DayOfWeek.SUNDAY) {
next = next.plusDays(1);
}
return next;
});
public static void main(String[] args) {
LocalDate tuesday = LocalDate.of(2024, 11, 5);
LocalDate friday = LocalDate.of(2024, 11, 8);
System.out.println(tuesday.with(NEXT_WORKING_DAY)); // 2024-11-06
System.out.println(friday.with(NEXT_WORKING_DAY)); // 2024-11-11
}
}You keep the adjuster in a named constant, so you can reuse it anywhere. Reading date.with(NEXT_WORKING_DAY) tells the next programmer exactly what the line does.
Combining Adjusters with Other Methods
Adjusters work well with plus and minus methods because each call returns a new object. For example, "the last day of next month" is:
LocalDate result = date.plusMonths(1).with(TemporalAdjusters.lastDayOfMonth());From 2024-11-05, this gives 2024-12-31. You read the chain from left to right. First move one month ahead, then jump to the end of that month.
Summary
- A
TemporalAdjusteris a rule that returns a changed copy of a date. - You apply it with
with(...)and must keep the returned value. TemporalAdjustershas ready-made rules for month ends, year ends, and days of the week.nextskips today, whilenextOrSamecan return today.- Adjusters keep the time and zone, handle leap years, and fail at run time on
LocalTime. ofDateAdjusterlets you write your own reusable rules.
Exercise
Starting from LocalDate.of(2024, 11, 5), write one line of code that finds the first Monday of December 2024. What date does it print?
Show answer
date.with(TemporalAdjusters.firstDayOfNextMonth()).with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)) prints 2024-12-02. The first call moves to December 1, and the second moves to the first Monday in that month.
Exercise
Today is Friday, 2024-11-08. What do date.with(TemporalAdjusters.next(DayOfWeek.FRIDAY)) and date.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY)) return?
Show answer
next(FRIDAY) returns 2024-11-15 because it never returns the starting day. nextOrSame(FRIDAY) returns 2024-11-08 because the starting day is already a Friday.
Exercise
A programmer writes date.with(TemporalAdjusters.lastDayOfMonth()); and then prints date, but sees the original date. Why, and how do you fix it?
Show answer
LocalDate is immutable, so with() returns a new object and leaves date unchanged. The result was thrown away. Fix it by keeping the result: date = date.with(TemporalAdjusters.lastDayOfMonth());