Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two dates based on year-month, taking no notice of day

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 return true but will return false because 2011 < 2012 but 10 !< 09

If I use a OR instead of a AND, it's still wrong:

  • 2013-01 LTE 2012-05 should return false but will return true because 2013 !< 2012 but 01 < 05

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

like image 597
sp00m Avatar asked Sep 18 '12 12:09

sp00m


People also ask

How do I compare two date by month and day in Excel?

Here is another shorter formula also can help you: =(A2-DAY(A2))=(B2-DAY(B2)). 2. In the formulas, A2 and B2 is the two dates that you want to compare, please change the cell references as your need.

How do you compare two dates without the time portion?

If you want to compare only the month, day and year of two dates, following code works for me: SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); sdf. format(date1). equals(sdf.

How do you compare two dates using a moment?

We can use the isAfter method to check if one date is after another. We create a moment object with a date string. Then we call isAfter on it with another date string and the unit to compare.

How do I compare 2 months in Excel?

As below screenshot shown, supposing you need to compare two date lists and match the dates by month and year only, you can apply the below formula to achieve it. 1. Select a blank cell, enter formula =MONTH(A2)&YEAR(A2)=MONTH(B2)&YEAR(B2) into the Formula Bar, and then press the Enter key.


1 Answers

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.

like image 171
Ivan Koblik Avatar answered Sep 30 '22 07:09

Ivan Koblik