In this topic, we will discuss easily and interestingly how to print calendar of a month in Java programming. Lets see the methods and function what will be used to print calendar month in Java programming.
Calendar Of A Month
Table of Contents:
- Introduction
- Program
- Output
- Conclusion
Introduction:
Printing a calendar of a specific month in Java involves generating and formatting the dates for that month. Java provides classes like ‘Calendar' and ‘GregorianCalendar' to handle date calculations and formatting with ‘SimpleDateFormat'.
Here’s a straightforward example to print a calendar for a given month:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendarExample {
public static void main(String[] args) {
int year = 2024;
int month = Calendar.JULY; // Note: Calendar.JULY is 6 (0-indexed)
Calendar calendar = new GregorianCalendar(year, month, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat sdf = new SimpleDateFormat("MMMM yyyy");
System.out.println(sdf.format(calendar.getTime()));
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
calendar.set(Calendar.DAY_OF_MONTH, 1);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // 1 = Sunday, ..., 7 = Saturday
for (int i = 1; i < dayOfWeek; i++) {
System.out.print(" ");
}
for (int day = 1; day <= daysInMonth; day++) {
System.out.printf("%3d ", day);
calendar.add(Calendar.DAY_OF_MONTH, 1);
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println();
}
}
System.out.println();
}
}
Output:
July 2024
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
- Setting up the Calendar:
GregorianCalendaris used to set the year and month. We initialize it with the desired year and month (usingCalendar.JULYwhich corresponds to month 6, as months in Java are 0-indexed). - Getting Days in Month:
calendar.getActualMaximum(Calendar.DAY_OF_MONTH)gives the number of days in the specified month.
Conclusion:
In this conclusion, Java programming provides flexible methods and functions to print calendar month in Java. This example prints a simple textual representation of a calendar for a specified month and year in Java. Adjustments can be made for different formats or additional features, such as highlighting the current day or including events.