Java Calendar Compare compareDates(Calendar date1, Calendar date2)

Here you can find the source of compareDates(Calendar date1, Calendar date2)

Description

Method that compares 2 dates, works similarly to the compareTo method from Calendar, but ignores the time, just uses the year, month and day

License

Open Source License

Parameter

Parameter Description
date1 a parameter
date2 a parameter

Return

0 if the dates represent the same day, -1 if date1 is before date2, 1 if date1 is after date2

Declaration

public static int compareDates(Calendar date1, Calendar date2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Calendar;

public class Main {
    /**/*  w ww  . j a va2 s  . c  om*/
     * Method that compares 2 dates, works similarly to the compareTo method from Calendar, but 
     * ignores the time, just uses the year, month and day
     * @param date1
     * @param date2
     * @return 0 if the dates represent the same day, -1 if date1 is before date2, 1 if date1 is 
     * after date2 
     */
    public static int compareDates(Calendar date1, Calendar date2) {
        int result = 0;
        if (date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR)) {
            if (date1.get(Calendar.MONTH) == date2.get(Calendar.MONTH)) {

                if (date1.get(Calendar.DAY_OF_MONTH) == date2
                        .get(Calendar.DAY_OF_MONTH)) {
                    result = 0;
                } else if (date1.get(Calendar.DAY_OF_MONTH) < date2
                        .get(Calendar.DAY_OF_MONTH)) {
                    result = -1;
                } else if (date1.get(Calendar.DAY_OF_MONTH) > date2
                        .get(Calendar.DAY_OF_MONTH)) {
                    result = 1;
                }
            } else if (date1.get(Calendar.MONTH) < date2
                    .get(Calendar.MONTH)) {
                result = -1;
            } else if (date1.get(Calendar.MONTH) > date2
                    .get(Calendar.MONTH)) {
                result = 1;
            }

        } else if (date1.get(Calendar.YEAR) < date2.get(Calendar.YEAR)) {
            result = -1;
        } else if (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) {
            result = 1;
        }

        return result;
    }
}

Related

  1. compare(Calendar c1, Calendar c2)
  2. compare(Calendar c1, Calendar c2)
  3. compare(Calendar c1, Calendar c2, int what)
  4. compareCalendar(Calendar cal1, Calendar cal2)
  5. compareDates(final Calendar firstCal, final Calendar secondCal)
  6. compareDateTime(final Calendar firstCal, final Calendar secondCal)
  7. compareDay(Calendar calendar, Calendar calendar1)
  8. compareSameDay(Calendar first, Calendar second)