Java Program to display curent month calender.
Objective
Write a Java program to display the calendar for the current month on the console.
Algorithm / Approach
- Instantiate a
GregorianCalendar. - Extract the current day, month, and the first day of the week.
- Set the calendar to the 1st day of the month using
d.set(Calendar.DAY_OF_MONTH, 1). - Print the Days of the Week header using
DateFormatSymbols. - Print empty spaces until the start day of the week is reached.
- Loop through the days, printing each one, adding an asterisk if it is the current day, and breaking to a new line at the end of the week.
ShowCalendar.java
import java.util.*;
import java.text.*;
import static java.util.Calendar.*;
class ShowCalendar {
public static void main(String[] args) {
GregorianCalendar d;
d = new GregorianCalendar();
int today = d.get(DAY_OF_MONTH);
int month = d.get(MONTH);
int weekFirstDay = d.getFirstDayOfWeek();
d.set(Calendar.DAY_OF_MONTH, 1);
int startDay = d.get(DAY_OF_WEEK);
DateFormatSymbols ob;
ob = new DateFormatSymbols();
String [] days = ob.getShortWeekdays();
for(int i=1;i< days.length;i++){
System.out.printf("%-4s",days[i]);
}
System.out.println("");
for(int i=1;i< startDay;i++){
System.out.print(" ");
}
while(true){
int day = d.get(DAY_OF_MONTH);
System.out.printf("%3d",day);
d.add(DAY_OF_MONTH,1);
if(day==today)
System.out.print("*");
else
System.out.print(" ");
if(d.get(DAY_OF_WEEK)==weekFirstDay)
System.out.println("");
if(month!=d.get(MONTH))break;
}
System.out.println("");
}
}
Expected Output
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
Explanation of the Program
- This program combines complex Date manipulation with precise Console formatting.
- The
GregorianCalendarclass provides advanced calendar calculations (like figuring out what day of the week a specific date falls on). We mathematically shift the cursor based on the week layout to draw a standard wall calendar.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)