Java Date Compare compareDate(Date d1, Date d2)

Here you can find the source of compareDate(Date d1, Date d2)

Description

Compares two dates.

License

BSD License

Parameter

Parameter Description
d1 - Date 1
d2 - Date 2

Return

0 if same, -1 if d1 is less than d2.

Declaration

public static int compareDate(Date d1, Date d2) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright SemanticBits, Northwestern University and Akaza Research
 * /*w ww  .  ja va 2 s .  c o m*/
 * Distributed under the OSI-approved BSD 3-Clause License.
 * See http://ncip.github.com/caaers/LICENSE.txt for details.
 ******************************************************************************/

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

public class Main {
    /**
     * Compares two dates. The time fields are ignored.
     * 
     * @param d1 -
     *                Date 1
     * @param d2 -
     *                Date 2
     * @return 0 if same, -1 if d1 is less than d2.
     */
    public static int compareDate(Date d1, Date d2) {

        if (d1 == null && d2 == null)
            return 0;
        if (d1 == null && d2 != null)
            return -1;
        if (d1 != null && d2 == null)
            return 1;

        Calendar c1 = Calendar.getInstance();
        c1.setTime(d1);

        Calendar c2 = Calendar.getInstance();
        c2.setTime(d2);

        int x = c1.get(Calendar.YEAR);
        int y = c2.get(Calendar.YEAR);
        if (x != y)
            return x - y;

        x = c1.get(Calendar.MONTH);
        y = c2.get(Calendar.MONTH);
        if (x != y)
            return x - y;

        x = c1.get(Calendar.DATE);
        y = c2.get(Calendar.DATE);
        return x - y;
    }
}

Related

  1. compare2Date(Date date1, Date date2)
  2. compare2Dates(Date d1, Date d2)
  3. compare2DateString(String DateStringType, String dateStr1, String dateStr2)
  4. compare_date2(String finalDate, String enddate)
  5. compareCalendars(Date fechaAComparar, Date fechaBase)
  6. compareDate(Date d1, Date d2)
  7. compareDate(Date d1, Date d2)
  8. CompareDate(Date date, Date otherdate)
  9. compareDate(Date date1)