Skip to content Skip to sidebar Skip to footer

How To Know If A Date Is Within The Same Day Of Other Date

If I have a two Dates in Java (Android) (Date1 and Date2), how can I know if the Date2 is within the same day of the Date1? (Note: not if the Date2-Date1 < 24 hours). Some examp

Solution 1:

Why don't you use DateUtils?

You can directly invoke methods like 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.


Solution 2:

I copied this from Java: comparing two Dates to see if they are in 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);

Post a Comment for "How To Know If A Date Is Within The Same Day Of Other Date"