Java Day Compare compareDateByDay(Date date1, Date date2)

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

Description

Days, compare the size of the two dates.

License

Open Source License

Parameter

Parameter Description
date1 Date
date2 Date

Return

int

Declaration

public static int compareDateByDay(Date date1, Date date2) 

Method Source Code


//package com.java2s;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Locale;

public class Main {
    /** this date format for internal use. **/
    private static final String DATEFORMAT_YYYYMMDD = "yyyyMMdd";

    /**// w w  w . j  a  v  a 2 s .  c o m
     * Days, compare the size of the two dates.
     * 
     * <pre>
     *  (20120105,20120109) --> -1
     *  (20120109,20120105) --> 1
     *  (20120109,20120109) --> 0
     *  
     * If any date is null by default to use a specific value(future:2222-02-02).
     * 
     * </pre>
     * 
     * 
     * @param date1 Date
     * @param date2 Date
     * @return int
     */
    public static int compareDateByDay(Date date1, Date date2) {
        if (date1 == null) {
            date1 = future();
        }
        if (date2 == null) {
            date2 = future();
        }
        String d1 = dateToString(date1, DATEFORMAT_YYYYMMDD);
        String d2 = dateToString(date2, DATEFORMAT_YYYYMMDD);
        return d1.compareTo(d2);

    }

    /**
     * Given a future date, default date format yyyy-MM-dd.
     * 
     * @return Date, will return 2222-02-02.
     */
    public static Date future() {
        Date date = null;
        try {
            DateFormat df = getDateFormat(DATEFORMAT_YYYYMMDD);
            date = df.parse(df.format(df.parse("22220202")));
        } catch (Exception e) {
            return null;
        }
        return date;
    }

    /**
     * Date converted to a string.
     * 
     * <pre>
     *  DateUtils.dateToString(new Date(0), "yyyyMMdd") --> 19700101
     * </pre>
     * 
     * @param date target date
     * @param pattern fomate pattern
     * @return String
     */
    public static String dateToString(Date date, String pattern) {
        return getDateFormat(pattern).format(date);
    }

    /**
     * return date format with Locale US.
     * 
     * @param pattern date format pattern.
     * @return DateFormat
     */
    public static DateFormat getDateFormat(String pattern) {
        return new SimpleDateFormat(pattern, Locale.US);
    }
}

Related

  1. afterNDay(int n)
  2. afterNDaysDate(String theDate, int nDayNum, String format)
  3. compareDay(Date first, Date second)
  4. compareInSameDay(Date date1, Date date2)
  5. isSameDay(Date a, Date b)
  6. isSameDay(Date c1, Date c2)