Temporal Adjuster Example: First In Year

Last modified on August 14th, 2014 by Joe.

If you are reading this temporal adjuster example series, you will find this example to be different from all others. This temporal adjuster is going to take an argument and adjust the value based on the argument passed.

For example, given an year what date falls on first Monday. This temporal adjuster takes the DayOfWeek as argument. This decides for which day like Monday or Tuesday or etc we want to find the date. If you have jumped directly into this tutorial, I recommend you to go through the introduction to temporal adjuster tutorial before reading through.

package com.javapapers.java8.dateandtime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;

public class FirstInYearTemporalAdjuster implements TemporalAdjuster {

	DayOfWeek dayOfWeek;

	public FirstInYearTemporalAdjuster(DayOfWeek dayOfWeek) {
		this.dayOfWeek = dayOfWeek;
	}

	@Override
	public Temporal adjustInto(Temporal temporalAdjusterInput) {
		LocalDate temporalAdjusterDate = LocalDate.from(temporalAdjusterInput);
		// reusing an already available TemporalAdjuster
		// and adjusting the calculated date
		TemporalAdjuster firstInMonthTemporalAdjuster = TemporalAdjusters
				.firstInMonth(dayOfWeek);
		LocalDate forYear = LocalDate.of(temporalAdjusterDate.getYear(), 1, 1);
		return forYear.with(firstInMonthTemporalAdjuster);
	}

	public static void main(String... strings) {
		LocalDate currentDate = LocalDate.now();
		FirstInYearTemporalAdjuster firstInYearTemporalAdjuster = new FirstInYearTemporalAdjuster(
				DayOfWeek.MONDAY);
		LocalDate adjustedDate = currentDate.with(firstInYearTemporalAdjuster);
		System.out.println("For year " + currentDate.getYear()
				+ ", first Monday is on " + adjustedDate);

	}
}

The DayOfWeek is passed as an argument in the constructer while instantiating the TemporalAdjuster object. One more thing to note in this example is, we have used already available TemporalAdjusters to derive the adjusted date.

Temporal Adjuster Example Program Output

For year 2014, first Monday is on 2014-01-06