Get the first Monday of a month in Java

https‮:‬//www.lautturi.com
Get the first Monday of a month in Java

To get the first Monday of a month in Java, you can use the Calendar class. Here's an example of how you could do this:

import java.util.Calendar;

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
System.out.println("First Monday of the month: " + calendar.getTime());

This code will set the calendar to the first Monday of the current month. You can change the month by setting the Calendar.MONTH field to the desired month before calling the set() method.

For example, to get the first Monday of September 2021, you can use the following code:

calendar.set(Calendar.MONTH, Calendar.SEPTEMBER);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
System.out.println("First Monday of September 2021: " + calendar.getTime());

This will output "First Monday of September 2021: Mon Sep 06 00:00:00 EDT 2021".

Note that the Calendar.DAY_OF_WEEK_IN_MONTH field specifies which week in the month the day of the week occurs. In this case, setting it to 1 means that it will select the first week in the month that has a Monday.

Created Time:2017-11-01 12:04:58  Author:lautturi