How to get the last thursday of the month in java

I need to get the date of the last Thursday of the month of any year, but the problem that I encountered is that for the month of dec'15last day is 31-dec-2015, but I get 24-dec-2015for the following code:

Date getLastThursday(def month, def year ) {
    Calendar cal = Calendar.getInstance();
    cal.set( year, month,1 )
    cal.add( Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK )%7+2) );
    return cal.getTime();
}

And also explain to me how this line of code works internally?

cal.add(Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK )%7+2))

+4
source share
2 answers

If you are using Java 8+, you can use the time regulator (part of the Java Time API):

int month = 12;
int year = 2015;
LocalDate lastThursday = LocalDate.of(year, month, 1).with(lastInMonth(THURSDAY));
System.out.println("lastThursday = " + lastThursday); //prints 2015-12-31

Note: Static Import Required

import static java.time.DayOfWeek.THURSDAY;
import static java.time.temporal.TemporalAdjusters.lastInMonth;

If you can’t use the new API, I suspect the problem is the module is working, and this should work:

//month should be 0-based, i.e. use 11 for December
static Date getLastThursday(int month, int year) {
  Calendar cal = Calendar.getInstance();
  cal.set(year, month + 1, 1);
  cal.add(Calendar.DAY_OF_MONTH, -((cal.get(Calendar.DAY_OF_WEEK) + 2) % 7));
  if (cal.get(Calendar.MONTH) != month) cal.add(Calendar.DAY_OF_MONTH, -7);
  return cal.getTime();
}

The second condition is to make sure we are back in a month.

+8

% :

cal.add( Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK )+2)%7 );

, -8 = > 24

+ 1

0

Source: https://habr.com/ru/post/1620105/


All Articles