Fluency of Java 8 Date-Time API

Here are a few quick examples of how API calls can be chained to answer advanced queries, such as “Which day is the last Friday of the next month”. Or imagine you need match a weekly or monthly schedule. These and similar queries can be resolved without much of an effort.


Simple queries can be solved by a mere call chaining.

Example #1 – Last Friday in February 2015

[java]
LocalDate date = LocalDate.now()
.withYear(2015)
.withMonth(2)
.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));

// Output: 2015-02-27
System.out.println(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
[/java]

LocalDate and DayOfWeek come from the standard java.time package. As you can see, the API allows for a range of date adjustments. TemporalAdjusters is a utility class which comes in handy when you need to apply additional filtering.

More involved queries can still be resolved with a fairly low level of complexity. Let me introduce a custom class called DateTimeWizard. The class encapsulates all the logic needed for the examples below.

Example #2 – Work days (disregards public holidays) in the given month

[java]
public class DateTimeWizard {
public List<LocalDate> workDays(int year, int month) {
LocalDate baseDate = LocalDate.now()
.withYear(year).withMonth(month);
LocalDate startDate = baseDate
.with(TemporalAdjusters.firstDayOfMonth());
LocalDate endDate = baseDate
.with(TemporalAdjusters.lastDayOfMonth());
List<LocalDate> workDays = new ArrayList<>();
while (!startDate.isAfter(endDate)) {
if (startDate.query(WorkDays::isWorkDay)) {
workDays.add(startDate);
}
startDate = startDate.plusDays(1);
}
return workDays;
}
static class WorkDays {
static boolean isWorkDay(TemporalAccessor date) {
int day = date.get(ChronoField.DAY_OF_WEEK);
return day >= 1 && day <= 5;
}
}
}
[/java]

Here is how we go about the implementation. First of all, we need to find the right point in time and milestones, which is represented by lines 3 – 8. Notice the use of TemporalAdjusters on lines 6 and 8.

Once we know the ranges we iterate within the found time span on a daily basis and determine if the given day is indeed a work day or not (lines 10 – 15). Since the WorkDays class exposes a static method, we can invoke it via a lambda expression (line 11).

Let’s move to the last example dealing with a weekly schedule.

Example #3 – All days falling into a weekly schedule for the whole month

[java]
public class DateTimeWizard {
public List<LocalDate> schedule(int year, int month, DayOfWeek… daysOfWeek) {
LocalDate baseDate = LocalDate.now()
.withYear(year).withMonth(month);
LocalDate startDate = baseDate
.with(TemporalAdjusters.firstDayOfMonth());
LocalDate endDate = baseDate
.with(TemporalAdjusters.lastDayOfMonth());
WeeklySchedule schedule = new WeeklySchedule(daysOfWeek);
List<LocalDate> scheduledDays = new ArrayList<>();
while (!startDate.isAfter(endDate)) {
if (startDate.query(schedule)) scheduledDays.add(startDate);
startDate = startDate.plusDays(1);
}
return scheduledDays;
}
private class WeeklySchedule implements TemporalQuery<Boolean> {
private DayOfWeek[] daysOfWeek;
WeeklySchedule(DayOfWeek[] daysOfWeek) {
this.daysOfWeek = daysOfWeek;
}
@Override
public Boolean queryFrom(TemporalAccessor date) {
boolean scheduled = false;
int day = date.get(ChronoField.DAY_OF_WEEK);
for (DayOfWeek dayOfWeek : daysOfWeek) {
if (dayOfWeek.get(ChronoField.DAY_OF_WEEK) == day) {
scheduled = true;
break;
}
}
return scheduled;
}
}
}
[/java]

Even though the approach is pretty much identical with the previous example (Example #2),
there is one subtle difference. The WeeklySchedule class encapsulating the query logic doesn’t expose a static method anymore. Also note that it implements a TemporalQuery interface. The reason for that is the state (a range of scheduled week days) which makes us instantiate the query in advance and provide the intended schedule to it (line 9).

Full source code, including a bunch of unit tests, is available on github. There is one more case, I haven’t described in here, which you might find interesting and that’s a bi-weekly schedule. Check the oddEvenWeekSchedule method of the class DateTimeWizard.

That’s about it. I hope I gave you an idea of how to use the API to your own advantage when it comes to dealing with various time constraints.

Similar Posts