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
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023