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);
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:
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.