How to find out if a date is on the same day of another date

If I have two dates in Java (Android) (Date1 and Date2), how can I find out if Date2 is on the same day as Date1? (Note: not if Date2-Date1 and 24 hours). Some examples (support for the same month and year)

 Date1: day=14 hour=00:00           Date2: day=14 hour=00:00    --> Result TRUE
 Date1: day=13 hour=23:59           Date2: day=14 hour=00:00    --> Result FALSE
 Date1: day=14 hour=05:00           Date2: day=14 hour=00:00    --> Result TRUE
 Date1: day=14 hour=00:00           Date2: day=15 hour=00:00    --> Result FALSE

thank

+3
source share
2 answers

Why aren't you using DateUtils?

You can directly refer to methods such as isSameDay

if (DateUtils.isSameDay(date1, date2)) {
    System.out.println("Same Date");
} else if (date1.before(date2)) {
    System.out.println("date1 before date2");
} else {
    System.out.println("date1 after date2");
}

Check Apache DateUtils .

+10
source

I copied this from Java: comparing two dates to see if they are on the same day

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                  cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
+4
source

All Articles