A Java Month class (that can be used in a calendar application)

Summary: This blog post shares some source code for a Java Month class that you can use in your applications, such as a Java calendar applications.

I was just cleaning up some old bits, and ran across a Java Month class that I've used on several calendar-related projects. If you happen to be working on a Java calendar application, and need a class to represent the months in a year, this source code may be helpful, so I thought I'd share it here.

Java Month class source code

Without any further ado then, here is the source code for this Java Month class:

package com.devdaily.calendar;

import java.util.Calendar;
import java.util.HashMap;

/**
 * A Java “Month” class which can be used in a calendar application,
 * such as our JSP Calendar.
 */
public class Month
{
  private int month;
  private int year;
  private int days[][];
  private int numberOfWeeks;
  private static HashMap months = new HashMap();

  /**
   * This constructor is private so callers will use the 
   * public "getMonth" methods.
   */
  private Month()
  {
  }

  /**
   * This constructor is private so callers will use the 
   * public "getMonth" methods.
   */
  private Month(int month, int year)
  {
    days = new int[6][7];
    numberOfWeeks = 0;
    this.month = month;
    this.year = year;
    buildWeeks();
  }

  public int getMonth()
  {
    return month;
  }

  /**
   * Call this method to get a Month object to work with.
   */
  public static Month getMonth(int month, int year)
  {
    String key = String.valueOf((new StringBuffer(String.valueOf(month))).append("/").append(year));
    if (months.containsKey(key))
    {
      return (Month) months.get(key);
    }
    else
    {
      Month newMonth = new Month(month, year);
      months.put(key, newMonth);
      return newMonth;
    }
  }

  private void buildWeeks()
  {
    Calendar c = Calendar.getInstance();
    c.setFirstDayOfWeek(1);
    c.set(year, month, 1);
    for (; c.get(2) == month; c.add(5, 1))
    {
      int weekNumber = c.get(4) - 1;
      int dayOfWeek = calculateDay(c.get(7));
      days[weekNumber][dayOfWeek] = c.get(5);
      numberOfWeeks = weekNumber;
    }
  }

  public int calculateDay(int day)
  {
    if (day == 1)
      return 0;
    if (day == 2)
      return 1;
    if (day == 3)
      return 2;
    if (day == 4)
      return 3;
    if (day == 5)
      return 4;
    if (day == 6)
      return 5;
    return day != 7 ? 7 : 6;
  }

  public int[][] getDays()
  {
    return days;
  }

  public int getNumberOfWeeks()
  {
    return numberOfWeeks + 1;
  }

  public int getYear()
  {
    return year;
  }

}

I'm not going to take the time to explain this source code at this time, but if you'd like to see some more code that demonstrates the use of this Java Month class, please take a look at my Java JSP calendar (web calendar) project. The JSP files in that project will show you everything you need to work with months, years, etc.