You can use following solution. By changing calendar.set(Calendar.MONTH, Calendar.NOVEMBER)
, it should be usable for any month:
public int getLastFridayOfNovember() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Calendar.NOVEMBER);
int totalDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, totalDaysInMonth);
int daysToRollBack = (calendar.get(Calendar.DAY_OF_WEEK) + 1) % 7;
return totalDaysInMonth - daysToRollBack;
}
Usage is simple:
...
int lastDayOfNovember = getLastFridayOfNovember();
If you use Kotlin, it can be extension function as well:
fun Calendar.getLastFridayOfMonth(): Int {
val totalDaysInMonth = getActualMaximum(Calendar.DAY_OF_MONTH)
this[Calendar.DAY_OF_MONTH] = totalDaysInMonth
val daysToRollBack = (this[Calendar.DAY_OF_WEEK] + 1) % 7
return totalDaysInMonth - daysToRollBack
}
Usage:
val calendar = Calendar.getInstance()
// set month
calendar.set(Calendar.MONTH, Calendar.NOVEMBER);
// get last Friday of given month
val lastFridayOfNovember = calendar.getLastFridayOfMonth()