Compare two dates by year, not paying attention to the day

I need to be able to compare two dates, only depending on the year and month (i.e. not noticing the day), as well as in JAVA and HQL.

Let's say I need to check if less d1or equal 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 both parts of the code above, but this is incorrect:

  • 2011-10 LTE 2012-09must return true, but will return false, because 2011 < 2012, but10 !< 09

If I use ORinstead AND, it is still wrong:

  • 2013-01 LTE 2012-05must return false, but will return true, because 2013 !< 2012, but01 < 05

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

+5
source share
1 answer

That 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 thing for Java:

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

You can save the second check as y1 <= y2, but it will be a little redundant.

+6
source

All Articles