Compare two dates based on year-month, taking no notice of day
-
02-07-2021 - |
Pergunta
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 returntrue
but will returnfalse
because2011 < 2012
but10 !< 09
If I use a OR
instead of a AND
, it's still wrong:
2013-01 LTE 2012-05
should returnfalse
but will returntrue
because2013 !< 2012
but01 < 05
So, how should I process? Please, I need it for JAVA and HQL.
Solução
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.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow