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-09should returntruebut will returnfalsebecause2011 < 2012but10 !< 09
If I use a OR instead of a AND, it’s still wrong:
2013-01 LTE 2012-05should returnfalsebut will returntruebecause2013 !< 2012but01 < 05
So, how should I process? Please, I need it for JAVA and HQL.
This should work.
Same for Java:
You could keep second check as
y1 <= y2but it would be a little redundant.