Java Program To Print All The Dates In A Month That Fall On A Weekend
Chapter:
Miscellaneous
Last Updated:
19-09-2023 16:56:39 UTC
Program:
/* ............... START ............... */
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
public class WeekendDatesInMonth {
public static void main(String[] args) {
int year = 2023; // Change this to the desired year
Month month = Month.SEPTEMBER; // Change this to the desired month
// Iterate through the days of the specified month and year
LocalDate date = LocalDate.of(year, month, 1);
LocalDate endDate = LocalDate.of(year, month, month.length(false));
while (!date.isAfter(endDate)) {
// Check if the day is Saturday or Sunday
if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY) {
System.out.println(date);
}
// Move to the next day
date = date.plusDays(1);
}
}
}
/* ............... END ............... */
Output
Let's assume we want to print all the weekend dates for the month of September 2023.
Here's the sample output of the Java program:
2023-09-02
2023-09-03
2023-09-09
2023-09-10
2023-09-16
2023-09-17
2023-09-23
2023-09-24
2023-09-30
Notes:
-
You specify the year and month for which you want to print weekend dates by changing the values of the year and month variables.
- We use a while loop to iterate through all the days of the specified month and year.
- For each day, we check if it falls on a Saturday or Sunday using the getDayOfWeek() method from the LocalDate class.
- If the day is a Saturday or Sunday, we print it to the console.
- We then move to the next day using the plusDays(1) method to continue checking the remaining days of the month.
- Compile and run this Java program, and it will print all the dates in the specified month that fall on a weekend.
Tags
Java program to print all the dates in a month that fall on a weekend In Java, Java get all weekend dates in a given month