TemporalAdjusters lastInMonth() method in Java with Examples
The lastInMonth(DayOfWeek) method of the TemporalAdjusters class yields a TemporalAdjuster object, which can be utilized to derive a new Date object from any Date object to which this TemporalAdjuster is applied. This new Date object is the final date of the same month with the parameter-passed matching DayOfWeek.
Change the day of the week or the month, depending on what we require, to find the latest occurrence of a specific day within a month.
Syntax:
public static TemporalAdjuster lastInMonth(DayOfWeek dayOfWeek)
Parameters: The last date of the exact same month with the exact matching DayOf Week is the new Date object that can be obtained using this method, which accepts dayOfWeek (parameter).
Return value: This approach returns the last adjuster for the month rather than null.
Algorithm:
Step 1: Identifying the Week's Target Day
The DayOfWeek enum is the argument passed to the Temporal Adjusters.lastInMonth() method, which indicates which day of the week should be searched for within the month.
Step 2: The Calculation of the Last Occurrence
The TemporalAdjuster instance returned by lastInMonth() analyses the given month and determines the last occurrence of the specified day-of-the-week when applied to a LocalDate object using the with() method.
Step 3: Date Adjustment
The TemporalAdjuster takes the given date and changes it to the date of the last instance of the given day-of-the-week in that month. It then returns the modified LocalDate.
Step 4: Usage and Obtaining Results
When applied to a LocalDate object, the modified date has the value that indicates the day of the week that occurred the last time in the specified month. After that, we can utilise this updated date in your program-as needed.
Implementation:
FileName: TemporalExample.java
import java.util.*;
import java.time.*;
import java.time.temporal.*;
import java.io.*;
public class TemporalExample
{
public static void main(String[] args)
{
// get TemporalAdjuster using
//The last adjuster for the month
TemporalAdjuster Temporal = TemporalAdjusters.lastInMonth(
DayOfWeek.THURSDAY);
//utilizing a local date-time adjuster
LocalDate Date = LocalDate.of(2023, 12, 07);
LocalDate lastInMonth = Date.with(Temporal);
System.out.println("The last date in the month having" + " thursday for localdate " + Date + " is: " + lastInMonth);
}
}
Output:
The last date in the month having thursday for localdate 2023-12-07 is: 2023-12-28