This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

I need to compare two dates (such as date1 and date2) and derive a Boolean sameDay, which is true for both dates that share the sameDay and false otherwise.

How can I do this? There seems to be some confusion here… And I want to avoid introducing dependencies other than the JDK as much as possible.

Note that sameDay is true if date1 and date2 share the same year, month, and day, otherwise false. I realized that it takes knowing the time zone…

Take a chestnut


date1 = 2008 Jun 03 12:56:03
date2 = 2008 Jun 03 12:59:44
  => sameDate = true

date1 = 2009 Jun 03 12:56:03
date2 = 2008 Jun 03 12:59:44
  => sameDate = false

date1 = 2008 Aug 03 12:00:00
date2 = 2008 Jun 03 12:00:00
  => sameDate = false
Copy the code

Answer 1:

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
                  cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
Copy the code

Note that “same day” is not a simple concept, but sounds simple when it comes to different simultaneuses. The code above computes dates for both dates relative to the time zone used by the computer on which they are running. If this is not what you need, the relevant time zone must be passed to the calendar.getInstance () call after determining exactly what “same day” means.

Yes, Joda Time’s LocalDate can make the whole process a lot cleaner and easier (although the same difficulties involve Time zones).

This article translation to Stack OverFlow:stackoverflow.com/questions/2…