Java Date Compare compare(Date d1, Date d2)

Here you can find the source of compare(Date d1, Date d2)

Description

compare

License

Open Source License

Declaration

public static String compare(Date d1, Date d2) 

Method Source Code

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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    /**//from   w ww  .j  av a  2  s  .  c  om
     * yyyy-MM-dd
     */
    static public final String FORMAT_DATE_ONLY = "yyyy-MM-dd";

    public static String compare(Date d1, Date d2) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d1);

        Calendar c2 = Calendar.getInstance();
        c2.setTime(d2);

        if (c1.after(c2)) {
            return ">";
        } else if (c1.before(c2)) {
            return "<";
        } else {
            return "=";
        }
    }

    public static String compare(String s1, String s2) {
        Date d1 = parse(s1, FORMAT_DATE_ONLY);
        Date d2 = parse(s2, FORMAT_DATE_ONLY);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(d1);
        c2.setTime(d2);
        if (c1.after(c2)) {
            return ">";
        } else if (c1.before(c2)) {
            return "<";
        } else {
            return "=";
        }
    }

    public static Date parse(String str, String format) {
        try {
            SimpleDateFormat sf = new SimpleDateFormat(format);
            sf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            return sf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. after(String format, String baseDate, String compareDate)
  2. compare(Date d1, Date d2)
  3. compare(Date d1, Date d2)
  4. compare(Date date, Date fromDate, Date toDate)
  5. compare(Date date1, Date date2, String format)
  6. Compare(Date dtA, Date dtB, boolean bUnkIsPast)
  7. compare(Date start, Date end)