How do I use TemporalAdjusters dayOfWeekInMonth() method?
dayOfWeekInMonth() is a handy method in java.time.temporal.TemporalAdjusters class that returns an adjuster which changes the date to the n-th day of week in the current month. Here is an example of how you could use it: package org.kodejava.datetime; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; public class DayOfWeekInMonthExample { public static void main(String[] args) { // […]
Article by Wayan · Source: Kode Java ↗
dayOfWeekInMonth() is a handy method in java.time.temporal.TemporalAdjusters class that returns an adjuster which changes the date to the n-th day of week in the current month.
Here is an example of how you could use it:
package org.kodejava.datetime;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class DayOfWeekInMonthExample {
public static void main(String[] args) {
// Current date
LocalDate date = LocalDate.now();
// The 2nd Tuesday in the month of the date.
LocalDate secondTuesday = date.with(
TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY));
System.out.println("Current Date: " + date);
System.out.println("Second Tuesday: " + secondTuesday);
}
}
Output:
Current Date: 2024-01-18
Second Tuesday: 2024-01-09
This code would display the date of the second Tuesday in the current month.
Here’s what’s going on in this case:
TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY)specifies that we want the second occurrence ofDayOfWeek.TUESDAYin the current month.-
date.with(TemporalAdjuster)modifies the LocalDate date based on theTemporalAdjusterthat is passed in. The original date object is unchanged; a newLocalDatereflecting the adjusted date is returned.
This TemporalAdjusters method is very useful when you have conditional logic based on things like “if it’s the third Monday of the month, then…”
Comments 0
Share your questions, experiences, or feedback about this article.
Sign in with Google to leave a comment.
Sign in with Google
No comments yet. Be the first to share your feedback.