Get Last Friday of Month in Java
Let Calendar.class do its magic for you ;)
pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY);
pCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
Based on marked23's suggestion:
public Date getLastFriday( 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 ) % 7 + 1 ) );
return cal.getTime();
}
java.time
Using java.time library built into Java 8 and later, you may use TemporalAdjusters.lastInMonth
:
val now = LocalDate.now()
val lastInMonth = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))
You may choose any day from the DayOfWeek
enum.
If you need to add time information, you may use any available LocalDate
to LocalDateTime
conversion like
lastFriday.atStartOfDay() // e.g. 2015-11-27T00:00
You never need to loop to find this out. For determining the "last Friday" date for this month, start with the first day of next month. Subtract the appropriate number of days depending on what (numerical) day of the week the first day of the month falls on. There's your "last Friday." I'm pretty sure it can be boiled down to a longish one-liner, but I'm not a java dev. So I'll leave that to someone else.
I would use a library like Jodatime. It has a very useful API and it uses normal month numbers. And best of all, it is thread safe.
I think that you can have a solution with (but possibly not the shortest, but certainly more readable):
DateTime now = new DateTime();
DateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);
if (dt.getMonthOfYear() != now.getMonthOfYear()) {
dt = dt.minusDays(7);
}
System.out.println(dt);