Yahya Uddin Yahya Uddin - 1 month ago 6
Java Question

How to check if 2 dates are on the same day in Java

I have 2 Date variables, Date1 and Date2.
I want to check if Date 1 fall on the same date as Date2 (but they are allowed to have different times).

How do i do this?

It looks like a really easy thing to do, but i'm struggling.

EDIT: I want to avoid external libraries and stuff

EDIT:
My orgional idea was to remove the hour, min, sec but those features are marked as depreciated in Java. So what should I use????

Answer

Although given answers based on date component parts of a java.util.Date are sufficient in many parts, I would stress the point that a java.util.Date is NOT a date but a kind of UNIX-timestamp measured in milliseconds. What is the consequence of that?

Date-only comparisons of Date-timestamps will depend on the time zone of the context. For example in UTC time zone the date-only comparison is straight-forward and will finally just compare year, month and day component, see other answers (I don't need to repeat).

But consider for example the case of Western Samoa crossing the international dateline in 2011. You can have valid timestamps of type java.util.Date, but if you consider their date parts in Samoa you can even get an invalid date (2011-12-30 never existed in Samoa locally) so a comparison of just the date part can fail. Furthermore, depending on the time zone the date component can generally differ from local date in UTC zone by one day, ahead or behind, in worst case there are even two days difference.

So following extension of solution is slightly more precise:

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
fmt.setTimeZone(...); // your time zone
return fmt.format(date1).equals(fmt.format(date2));

Similar extension also exists for the more programmatic approach to first convert the j.u.Date-timestamp into a java.util.GregorianCalendar, then setting the time zone and then compare the date components.