Java Date Compare compare(Date d1, Date d2)

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

Description

Compares two dates taking into consideration only the year, month and day

License

Apache License

Parameter

Parameter Description
d1 the first date
d2 the second date

Return

a negative integer, zero, or a positive integer as d1 is less than, equal to, or greater than d2

Declaration

public static int compare(Date d1, Date d2) 

Method Source Code


//package com.java2s;
/*/*from   w w  w. ja v  a 2  s .co  m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    /**
     * Compares two dates taking into consideration only the year, month and day
     * @param d1 the first date
     * @param d2 the second date
     * @return a negative integer, zero, or a positive integer as
     * <code>d1</code> is less than, equal to, or greater than <code>d2</code>
     * @see java.util.Comparator
     * @see #after(Date, Date)
     * @see #before(Date, Date)
     */
    public static int compare(Date d1, Date d2) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d1);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(d2);

        if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) {
            if (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)) {
                return c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH);
            }
            return c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
        }
        return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
    }
}

Related

  1. after(String format, String baseDate, String compareDate)
  2. compare(Date d1, Date d2)
  3. compare(Date d1, Date d2)
  4. compare(Date date, Date fromDate, Date toDate)
  5. compare(Date date1, Date date2, String format)
  6. Compare(Date dtA, Date dtB, boolean bUnkIsPast)