FileDocCategorySizeDatePackage
MonthYear.javaAPI DocExample2214Sun Sep 02 14:59:06 BST 2001com.oreilly.forum.domain

MonthYear.java

package com.oreilly.forum.domain;

import java.io.Serializable;
import java.util.*;

/**
 * Represents a month and a year.
 */
public class MonthYear implements Comparable, Serializable {
    private int month;
    private int year;

    /**
     * Construct a new object representing the current instant in time.
     */
    public MonthYear() {
        this(new Date());
    }

    /**
     * Construct a new object with the given date.
     */
    public MonthYear(Date date) {
        this(DateUtil.getMonth(date), DateUtil.getYear(date));
    }

    /**
     * Construct a new object with the given month and year.
     * @param month a zero-based month, just like java.util.Calendar.
     */
    public MonthYear(int month, int year) {
        this.month = month;
        this.year = year;
    }

    /**
     * Compare this MonthYear object to another.
     */
    public int compareTo(Object obj) {
        MonthYear rhs = (MonthYear) obj;
        // first compare year
        if (this.year < rhs.year) {
            return -1;
        } else if (this.year > rhs.year) {
            return 1;
        }
        // then month
        if (this.month < rhs.month) {
            return -1;
        } else if (this.month > rhs.month) {
            return 1;
        }

        return 0;
    }

    /**
     * @return true if the specified date occurs sometime during this month.
     */
    public boolean containsInMonth(DayMonthYear date) {
        return date.getMonth() == this.month
                && date.getYear() == this.year;
    }

    /**
     * @return the month number, starting with 0 for January.
     */
    public int getMonth() {
        return this.month;
    }

    /**
     * @return the year number.
     */
    public int getYear() {
        return this.year;
    }

    public boolean equals(Object obj) {
        if (obj instanceof MonthYear) {
            MonthYear rhs = (MonthYear) obj;
            return this.month == rhs.month
                    && this.year == rhs.year;
        }
        return false;
    }

    public int hashCode() {
        return this.month ^ this.year;
    }
}