TemporalAdjusters.firstInMonth(DayOfWeek)
and TemporalAdjusters.lastInMonth(DayOfWeek)
methods are part of the java.time.temporal.TemporalAdjusters
class. They adjust the date to the first or last occurrence of the specified DayOfWeek
in the month.
Here’s an example of how to use these methods:
package org.kodejava.datetime;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class FirstLastInMonthExample {
public static void main(String[] args) {
// Get the current date
LocalDate date = LocalDate.now();
System.out.println("Current date: " + date);
LocalDate firstMondayInMonth = date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
System.out.println("First Monday of this month: " + firstMondayInMonth);
LocalDate lastFridayInMonth = date.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));
System.out.println("Last Friday of this month: " + lastFridayInMonth);
}
}
The output of the code snippet above:
Current date: 2024-01-18
First Monday of this month: 2024-01-01
Last Friday of this month: 2024-01-26
In this example:
- LocalDate.now()` is used to get the current date.
.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY))
adjusts the date to the first Monday of the current month..with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))
adjusts the date to the last Friday of the current month.
Latest posts by Wayan (see all)
- How do I create a servlet filter to make secure cookies? - April 18, 2024
- How do I configure secure cookies using web.xml? - April 18, 2024
- How do I create a table with multiple header in iText 8? - March 16, 2024