Java Date Compare compareDays(final Date date1, final Date date2)

Here you can find the source of compareDays(final Date date1, final Date date2)

Description

Compare two dates considering "day" as the most significant field.

License

Open Source License

Parameter

Parameter Description
date1 First date
date2 Second date

Return

If the first date is before the second date, a negative number will be returned. If the first date is same day of the second date, zero will be returned. If the first date is after the second date, a positive number will be returned

Declaration

public static int compareDays(final Date date1, final Date date2) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    private static final int[] DATE_FIELDS = new int[] { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_YEAR };

    /**// w w w.jav  a2 s.c o  m
     * Compare two dates considering "day" as the most significant field.
     * 
     * @param date1
     *            First date
     * @param date2
     *            Second date
     * @return If the first date is before the second date, a negative number
     *         will be returned. If the first date is same day of the second
     *         date, zero will be returned. If the first date is after the
     *         second date, a positive number will be returned
     */
    public static int compareDays(final Date date1, final Date date2) {
        Calendar calendar1 = getCalendarInstance(date1);
        Calendar calendar2 = getCalendarInstance(date2);
        for (int field : DATE_FIELDS) {
            int fieldValue1 = calendar1.get(field);
            int fieldValue2 = calendar2.get(field);
            if (fieldValue1 != fieldValue2) {
                return fieldValue1 - fieldValue2;
            }
        }
        return 0;
    }

    /**
     * Get the calendar instance of a given date
     * @param date
     * The date
     * @return The calendar instance
     */
    public static Calendar getCalendarInstance(final Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }
}

Related

  1. compareDateSequence(String startDate, String endDate)
  2. compareDatesOnly(long date1, long date2)
  3. compareDateTimeNull(Date d1, Date d2)
  4. compareDay(Date date, Date anotherDate)
  5. compareDay(Date date1, int compday)
  6. compareFileDates(final Date date1, final Date date2)
  7. compareMonth(Date first, Date second)
  8. compareSecond(java.util.Date date1, java.util.Date date2)
  9. compareStartDateEndDate(String startDate, String endDate)