Month Calendar

Java 1.5.2011 No Comments
Month Calendar

The following application shows how to format displaying a month in a way that would be suitable for including in a calendar.

This involves making sure days of the week are all vertically aligned, and that the first day of the week appears in the first column.

The day that is considered the first day of the week is not the same everywhere in the world. Instead of hard coding the first day of the week as either Sunday, Monday (or some other day) we instead use the Locale of the user to determine the first day of the week in that region.

The Locale is also used to get the day names to use as column headings on the first row.


package com.learnjava.util;

import java.util.Calendar;
import java.util.Locale;

public class MonthCalendar {

	private static void showMonth(Calendar cal) {
		int month = cal.get(Calendar.MONTH);
		int firstDayOfWeek = cal.getFirstDayOfWeek();

		// Display day names as headers

		cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
		for (int i=0; i<7; i++) {

			System.out.print(cal.getDisplayName(
				Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()));
			System.out.print(" ");
			cal.add(Calendar.DATE, 1);
		}
		System.out.println();

		// Display dates in month

		cal.set(Calendar.DATE, cal.getMinimum(Calendar.DATE));

		// Now display the dates, one week per line

		StringBuilder week = new StringBuilder();

		while (month==cal.get(Calendar.MONTH)) {

			// Display date

			week.append(String.format("%3d ", cal.get(Calendar.DATE)));

			// Increment date

			cal.add(Calendar.DATE, 1);

			// Check if week needs to be printed

			if (cal.get(Calendar.MONTH)!=month) {

				// end of month
				// just need to output the month

				System.out.println(week);

			} else if (cal.get(Calendar.DAY_OF_WEEK)==firstDayOfWeek) {

				// new week so print out the current week
				// first check if any padding needed

				int padding = 28-week.length();
				if (padding>0) {

					// pad out start of week

					week.insert(0, 
						String.format("%"+padding+"s", " "));
				}
				System.out.println(week);
				week.setLength(0);
			}
		}
	}
	
	public static void main(String[] args) {
		
		Calendar today = Calendar.getInstance();
		showMonth(today);

	}

}

Leave a Reply

s2Member®