Compares two Dates chronologically - Android java.util

Android examples for java.util:Date Compare

Description

Compares two Dates chronologically

Demo Code


//package com.java2s;

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

import java.util.TimeZone;

public class Main {
    /**//from   w w  w .ja v  a  2 s.c  o m
     * Compares two Dates chronologically
     *
     * @param date1 first Date to compare
     * @param date2 second Date to compare
     * @return 0 if equal, 1 if date1 is later, and -1 if date2 is later
     */
    public static int compareDates(Date date1, Date date2) {
        return (compareCalendars(dateToCalendar(date1),
                dateToCalendar(date2)));
    }

    /**
     * Compares two Calendars chronologically
     *
     * @param cal1 first Calendar to compare
     * @param cal2 second Calendar to compare
     * @return 0 if equal, 1 if cal1 is later, and -1 if cal2 is later
     */
    public static int compareCalendars(Calendar cal1, Calendar cal2) {
        //Cal 1 is after
        if (cal1.getTimeInMillis() < cal2.getTimeInMillis()) {
            return -1;
        }
        //Both calls equal
        else if (cal1.getTimeInMillis() == cal2.getTimeInMillis()) {
            return 0;
        }
        //Cal 1 is before
        else {
            return 1;
        }
    }

    /**
     * Converts a Date to a Calendar
     *
     * @param date date to convert
     * @return a calendar
     */
    public static Calendar dateToCalendar(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(date.getTime());
        cal.setTimeZone(TimeZone.getDefault());
        return cal;
    }
}

Related Tutorials