Compare two dates based on year-month, taking no notice of day

sp00m picture sp00m · Sep 18, 2012 · Viewed 7.4k times · Source

I need to be able to compare two dates, only based on the year and the month (i.e. without taking notice of the day), and that in JAVA and HQL.

Let's say I need to check if d1 is less than or equals d2. Here is what I tried:

JAVA

calendar.setTime(d1);
int y1 = calendar.get(Calendar.YEAR);
int m1 = calendar.get(Calendar.MONTH);
calendar.setTime(d2);
int y2 = calendar.get(Calendar.YEAR);
int m2 = calendar.get(Calendar.MONTH);
return y1 <= y2 && m1 <= m2;

HQL

select item from Item item
where year(item.d1) <= year(:d2)
and month(item.d1) <= month(:d2)

The algorithm is the same in the both pieces of code above, but it's wrong:

  • 2011-10 LTE 2012-09 should return true but will return false because 2011 < 2012 but 10 !< 09

If I use a OR instead of a AND, it's still wrong:

  • 2013-01 LTE 2012-05 should return false but will return true because 2013 !< 2012 but 01 < 05

So, how should I process? Please, I need it for JAVA and HQL.

Answer

Ivan Koblik picture Ivan Koblik · Sep 18, 2012

This should work.

select item from Item item
where year(item.d1) < year(:d2) or
     (year(item.d1) = year(:d2)
      and month(item.d1) <= month(:d2))

Same for Java:

y1 < y2 || (y1 == y2 && m1 <= m2)

You could keep second check as y1 <= y2 but it would be a little redundant.