Java Program To Find Number Of Working Days In A Month
Chapter:
Miscellaneous
Last Updated:
19-09-2023 16:50:51 UTC
Program:
/* ............... START ............... */
import java.util.Calendar;
public class WorkingDaysInMonth {
public static void main(String[] args) {
int year = 2023; // Replace with the desired year
int month = 9; // Replace with the desired month (1 = January, 2 = February, etc.)
int workingDays = countWorkingDays(year, month);
System.out.println("Number of working days in " + month + "/" + year + ": " + workingDays);
}
public static int countWorkingDays(int year, int month) {
int workingDays = 0;
Calendar calendar = Calendar.getInstance();
// Set the year and month in the calendar
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1); // Calendar uses 0-based months
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int day = 1; day <= daysInMonth; day++) {
// Set the day of the month
calendar.set(Calendar.DAY_OF_MONTH, day);
// Check if it's a working day (Monday to Friday)
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek >= Calendar.MONDAY && dayOfWeek <= Calendar.FRIDAY) {
workingDays++;
}
}
return workingDays;
}
}
/* ............... END ............... */
Output
/* Let's assume you want to find the number of working days in September 2023. Here's the
sample output for the Java program: */
Number of working days in 9/2023: 21
Notes:
-
To find the number of working days (business days) in a month using Java, you can follow these steps:
- Import the necessary Java libraries.
- Define a function to calculate the number of working days.
- Loop through each day in the given month.
- Check if each day is a working day (Monday to Friday).
- Increment a counter for each working day found.
- Display the total number of working days.
- Replace the year and month variables with the desired year and month for which you want to calculate the number of working days. This program uses the Calendar class to iterate through each day in the given month and counts the working days (Monday to Friday).