Compares two dates with/without considering time. - Java java.util

Java examples for java.util:Date Compare

Description

Compares two dates with/without considering time.

Demo Code


//package com.java2s;

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

public class Main {
    public static void main(String[] argv) throws Exception {
        Date parseDate = new Date();
        Date compareWithDate = new Date();
        boolean considerTime = true;
        System.out.println(compareDates(parseDate, compareWithDate,
                considerTime));//  w  w  w .jav a2s.c  o  m
    }

    /**
     * Compares two dates with/without considering time. Returns 0 if parseDate
     * = compareWithDate Returns 1 if parseDate < compareWithDate Returns 2 if
     * parseDate > compareWithDate
     * 
     * @param parseDate
     * @param compareWithDate
     * @param considerTime
     * @return
     */
    public static int compareDates(Date parseDate, Date compareWithDate,
            boolean considerTime) {

        if (!considerTime) {
            parseDate = getStartTimeOfDate(parseDate);
            compareWithDate = getStartTimeOfDate(compareWithDate);
        }

        int value = 0;

        if (isLessThan(parseDate, compareWithDate)) {
            value = 1;
        } else if (isGreaterThan(parseDate, compareWithDate)) {
            value = 2;
        } else {
            value = 0;
        }

        return value;
    }

    /**
     * methood to get the start time of a given day
     * 
     * @param date
     * @return
     */
    public static Date getStartTimeOfDate(Date date) {

        GregorianCalendar calander = new GregorianCalendar();
        calander.setTime(date);

        calander.set(GregorianCalendar.HOUR_OF_DAY, 0);
        calander.set(GregorianCalendar.MINUTE, 0);
        calander.set(GregorianCalendar.SECOND, 0);

        return calander.getTime();
    }

    public static boolean isLessThan(Date parseDate, Date compareWithDate) {
        boolean status = false;

        GregorianCalendar parseDate1 = getCalendar(parseDate);
        GregorianCalendar dateFrom = getCalendar(compareWithDate);

        if (parseDate1.before(dateFrom)) {
            status = true;
        }
        return status;
    }

    public static boolean isGreaterThan(Date parseDate, Date compareWithDate) {

        boolean status = false;
        // GregorianCalendar(int year, int month, int date, int hour, int
        // minute, int second)

        GregorianCalendar parseDate1 = getCalendar(parseDate);
        GregorianCalendar dateFrom = getCalendar(compareWithDate);

        if (parseDate1.after(dateFrom)) {
            status = true;
        }
        return status;
    }

    /**
     * 
     * @param date
     * @return
     */
    public static GregorianCalendar getCalendar(Date date) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return calendar;
    }
}

Related Tutorials