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

时间:2012-09-18 12:06:14

标签: java date compare hql 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;

HQL

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

上述两段代码中的算法相同,但错了:

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

如果我使用OR代替AND,那仍然是错误的:

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

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

1 个答案:

答案 0 :(得分:6)

这应该有用。

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

Java相同:

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

您可以将第二次检查设为y1 <= y2,但这有点多余。