How do I get the date of the first particular day after a specific date?

In this example we will learn how to get the date of the first particular day that fall after a specific date. In the code snippet below we will find the first Friday that fall after the new year of 2016. First let’s create a LocalDate object that represent the new year of 2016. We can use LocalDate.of() factory method to create the date object.

To get the first occurrence of a specific day-of-week from a date we create a TemporalAdjuster using the TemporalAdjusters.next() method and pass the day-of-week, in this case we pass DayOfWeek.FRIDAY.

After that we create another LocalDate that will hold the next Friday date. The get the date for the next Friday we call newYear.with() method and pass the TemporalAdjuster that we have created earlier.

Now, let’s try the code snippet below.

package org.kodejava.datetime;

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

public class GetFirstDayAfterDate {
    public static void main(String[] args) {
        // Obtains the current date.
        LocalDate newYear = LocalDate.of(2021, Month.JANUARY, 1);
        System.out.println("New Year = " + newYear);

        // Gets the next Friday.
        TemporalAdjuster nextFriday = TemporalAdjusters.next(DayOfWeek.FRIDAY);
        LocalDate nextFridayDate = newYear.with(nextFriday);
        System.out.printf("The first Friday after the new year of %s is %s%n",
                newYear, nextFridayDate);
    }
}

The code snippet will print out the following result:

New Year = 2021-01-01
The first Friday after the new year of 2021-01-01 is 2021-01-08
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.