Java Date Compare by Month isSameMonth(Date date1, Date date2)

Here you can find the source of isSameMonth(Date date1, Date date2)

Description

Compare the two dates whether are in the same month.

License

Open Source License

Parameter

Parameter Description
date1 the first date
date2 the second date

Return

whether are in the same month

Declaration

public static boolean isSameMonth(Date date1, Date date2) 

Method Source Code

//package com.java2s;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    /**//from  ww  w.  jav a 2  s. co m
     * Compare the two dates whether are in the same month.
     * 
     * @param date1
     *            the first date
     * @param date2
     *            the second date
     * @return whether are in the same month
     */
    public static boolean isSameMonth(Date date1, Date date2) {
        if (date1 == null && date2 == null)
            return true;
        if (date1 == null || date2 == null)
            return false;
        Calendar cal1 = GregorianCalendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = GregorianCalendar.getInstance();
        cal2.setTime(date2);
        return isSameMonth(cal1, cal2);
    }

    /**
     * Compare the two calendars whether they are in the same month.
     * 
     * @param cal1
     *            the first calendar
     * @param cal2
     *            the second calendar
     * @return whether are in the same month
     */
    public static boolean isSameMonth(Calendar cal1, Calendar cal2) {
        if (cal1 == null && cal2 == null)
            return true;
        if (cal1 == null || cal2 == null)
            return false;
        return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR))
                && (cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH));
    }
}

Related

  1. isSameMonth(Date date1, Date date2)
  2. isSameMonth(final Date d1, final Date d2)
  3. isSameMonth(final Date date1, final Date date2)
  4. monthsBetween(Date firstDate, Date secondDate)