In this tutorial we will learn about Find the date of first Saturday of a month in Java with some cool and easy examples.
Find the date of first Saturday of a month in Java
To find the date of the first Saturday of a month in Java, you can use the `java.time` package along with some simple logic. Here’s how you can do it:
import java.time.DayOfWeek;
import java.time.LocalDate;
public class FirstSaturdayOfMonth {
public static void main(String[] args) {
// Define the year and month for which you want to find the first Saturday
int year = 2024;
int month = 6; // June
// Create a LocalDate object representing the first day of the month
LocalDate firstDayOfMonth = LocalDate.of(year, month, 1);
// Find the day of the week for the first day of the month
DayOfWeek dayOfWeek = firstDayOfMonth.getDayOfWeek();
// Calculate the number of days to add to reach the first Saturday
int daysToAdd = DayOfWeek.SATURDAY.getValue() - dayOfWeek.getValue();
// Adjust if the first day of the month is already a Saturday
if (daysToAdd < 0) {
daysToAdd += 7;
}
// Calculate the date of the first Saturday of the month
LocalDate firstSaturday = firstDayOfMonth.plusDays(daysToAdd);
// Output the date of the first Saturday
System.out.println("Date of the first Saturday of " + firstSaturday.getMonth() + " " + year + " is: " + firstSaturday);
}
}
In this code:
– We define the year and month for which we want to find the first Saturday.
– We create a `LocalDate` object representing the first day of the month.
– We find the day of the week for the first day of the month.
– We calculate the number of days to add to reach the first Saturday by subtracting the day of the week of the first day from the value of `DayOfWeek.SATURDAY`.
– We adjust if the first day of the month is already a Saturday by adding 7 days to ensure we get the next Saturday.
– We calculate the date of the first Saturday by adding the calculated number of days to the first day of the month.
– Finally, we output the date of the first Saturday.
Benefits:
- Flexibility: This approach allows you to find the first Saturday of any given month and year.
- Readability: The code is concise and easy to understand.
- Accuracy: Leveraging the
java.timepackage ensures accuracy in date calculations.
Output:
Date of the first Saturday of JUNE 2024 is: 2024-06-01