I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Ja
Slightly easier to read, brute-force approach:
public int getLastFriday(int month, int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1, 0, 0, 0); // set to first day of the month
cal.set(Calendar.MILLISECOND, 0);
int friday = -1;
while (cal.get(Calendar.MONTH) == month) {
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?
friday = cal.get(Calendar.DAY_OF_MONTH);
cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days
} else {
cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day
}
}
return friday;
}