How to compare dates in Java? [duplicate]

2018-12-31 01:47发布

This question already has an answer here:

How do I compare dates in between in Java?

Example:

date1 is 22-02-2010
date2 is 07-04-2010 today
date3 is 25-12-2010

date3 is always greater than date1 and date2 is always today. How do I verify if today's date is in between date1 and date 3?

11条回答
低头抚发
2楼-- · 2018-12-31 02:12

This method worked for me:

 public static String daysBetween(String day1, String day2) {
    String daysBetween = "";
    SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {
        Date date1 = myFormat.parse(day1);
        Date date2 = myFormat.parse(day2);
        long diff = date2.getTime() - date1.getTime();
        daysBetween = ""+(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return daysBetween;
}
查看更多
不流泪的眼
3楼-- · 2018-12-31 02:15

Update for Java 8 and later

These methods exists in LocalDate, LocalTime, and LocalDateTime classes.

Those classes are built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

查看更多
冷夜・残月
4楼-- · 2018-12-31 02:18

You can use Date.getTime() which:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

This means you can compare them just like numbers:

if (date1.getTime() <= date.getTime() && date.getTime() <= date2.getTime()) {
    /*
     * date is between date1 and date2 (both inclusive)
     */
}

/*
 * when date1 = 2015-01-01 and date2 = 2015-01-10 then
 * returns true for:
 * 2015-01-01
 * 2015-01-01 00:00:01
 * 2015-01-02
 * 2015-01-10
 * returns false for:
 * 2014-12-31 23:59:59
 * 2015-01-10 00:00:01
 * 
 * if one or both dates are exclusive then change <= to <
 */
查看更多
何处买醉
5楼-- · 2018-12-31 02:18

Try this

public static boolean compareDates(String psDate1, String psDate2) throws ParseException{
        SimpleDateFormat dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
        Date date1 = dateFormat.parse(psDate1);
        Date date2 = dateFormat.parse(psDate2);
        if(date2.after(date1)) {
            return true;
        } else {
            return false;
        }
    }
查看更多
情到深处是孤独
6楼-- · 2018-12-31 02:23

Use getTime() to get the numeric value of the date, and then compare using the returned values.

查看更多
登录 后发表回答