比较两个日期基于年月,不注意一天

sp0*_*00m 5 java compare hql date date-comparison

我需要能够比较两个日期,仅基于年份和月份(即没有注意到当天),以及JAVA和HQL中的日期.

假设我需要检查是否d1小于或等于d2.这是我尝试过的:

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;
Run Code Online (Sandbox Code Playgroud)

HQL

select item from Item item
where year(item.d1) <= year(:d2)
and month(item.d1) <= month(:d2)
Run Code Online (Sandbox Code Playgroud)

上面两段代码中的算法都是一样的,但是错了:

  • 2011-10 LTE 2012-09应该返回,true但会返回,false因为2011 < 2012但是10 !< 09

如果我用a OR而不是a AND,它仍然是错误的:

  • 2013-01 LTE 2012-05应该返回,false但会返回,true因为2013 !< 2012但是01 < 05

那么,我应该如何处理?拜托,我需要它用于JAVA和HQL.

Iva*_*lik 6

这应该工作.

select item from Item item
where year(item.d1) < year(:d2) or
     (year(item.d1) = year(:d2)
      and month(item.d1) <= month(:d2))
Run Code Online (Sandbox Code Playgroud)

与Java相同:

y1 < y2 || (y1 == y2 && m1 <= m2)
Run Code Online (Sandbox Code Playgroud)

你可以保留第二次检查,y1 <= y2但这有点多余.