Java Date Between between(Date d, Date startDate, Date endDate)

Here you can find the source of between(Date d, Date startDate, Date endDate)

Description

Checks whether the given d, is greater than or equal to startDate and less than or equal to endDate.

License

BSD License

Parameter

Parameter Description

Return

if d or startDate is null

Declaration

public static boolean between(Date d, Date startDate, Date endDate) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright SemanticBits, Northwestern University and Akaza Research
 * //w ww.j  a v a  2  s .c om
 * 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 {
    /**
     * Checks whether the given d, is greater than or equal to startDate and less than or equal to endDate.
     * @param d, cannot be null
     * @param startDate, cannot be null
     * @param endDate, if null ignored
     * @return
     * {@link NullPointerException} if d or startDate is null
     */
    public static boolean between(Date d, Date startDate, Date endDate) {
        if (endDate == null) {
            return compareDate(d, startDate) >= 0;
        } else if (compareDate(endDate, d) == 0) {
            return false;
        } else {
            return compareDate(d, startDate) >= 0 && compareDate(d, endDate) <= 0;
        }
    }

    /**
     * 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. between(Date beginDate, Date endDate)
  2. between(Date kezdet, Date veg, Date datum)
  3. between(Date since, Date until, Date dateIn, Date dateOut)
  4. between(Date smdate, Date bdate)
  5. betweenDate(String from, String to)