Write a Java Program to Generate Month Calendar of Any Year


This Java program takes input of a month and year from the user, and displays a calendar for that month. It uses the Java 8 Date-Time API to get the number of days in the month, the day of the week for the first day of the month, and to format and display the calendar.

The display_Month method takes two arguments - the year and month entered by the user. It first creates a YearMonth object using the of method of the YearMonth class. This object represents the year and month entered by the user.

Then, it prints the header of the calendar - the names of the days of the week. It then calculates the day of the week for the first day of the month, using the getDayOfWeek method of the LocalDate class. If the day of the week is not Sunday (represented by the value 7), it prints blank spaces to align the first day of the month with the correct column of the calendar.

Finally, it uses a loop to print the dates of the month, using the printf method to format the output. It also checks if the current date is a multiple of 7, to print a new line and start a new row of the calendar.

Source Code

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.Scanner;
 
public class Calendar_Month
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter Month between 1 and 12 : ");
		int m = input.nextInt();
		System.out.print("Enter a Full Year : ");
		int y = input.nextInt();
		display_Month(y, m);
	}
 
	static void display_Month(int y, int m)
	{
		YearMonth ym = YearMonth.of(y, m);
		System.out.println("\n---------------------------");
		System.out.println("Sun Mon Tue Wed Thu Fri Sat");
		System.out.println("---------------------------");
		int cou = 1;
		int day = LocalDate.of(y, m, 1).getDayOfWeek().getValue();
		if (day != 7)
			for (int i = 0; i < day; i++, cou++)
			{
				System.out.printf("%-4s", "");
			}
 
		for (int i = 1; i <= ym.getMonth().length(ym.isLeapYear()); i++, cou++)
		{
			System.out.printf("%-4d", i);
			if (cou % 7 == 0)
			{
				System.out.println();
			}
		}		
		System.out.println("\n---------------------------");
    }
}

Output

Enter Month between 1 and 12 : 10
Enter a Full Year : 2023

---------------------------
Sun Mon Tue Wed Thu Fri Sat
---------------------------
1   2   3   4   5   6   7
8   9   10  11  12  13  14
15  16  17  18  19  20  21
22  23  24  25  26  27  28
29  30  31
---------------------------

Example Programs