Time: How to get the next friday?
It's possible to do it in a much easier to read way:
if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
return d.withDayOfWeek(DateTimeConstants.FRIDAY));
} else if (d.getDayOfWeek() == DateTimeConstants.FRIDAY) {
// almost useless branch, could be merged with the one above
return d;
} else {
return d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
}
or in a bit shorter form
private LocalDate calcNextFriday(LocalDate d) {
if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
d = d.withDayOfWeek(DateTimeConstants.FRIDAY));
} else {
d = d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
}
return d; // note that there's a possibility original object is returned
}
or even shorter
private LocalDate calcNextFriday(LocalDate d) {
if (d.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
d = d.plusWeeks(1);
}
return d.withDayOfWeek(DateTimeConstants.FRIDAY);
}
PS. I didn't test the actual code! :)
java.time
With the java.time framework built into Java 8 and later (Tutorial) you can use TemporalAdjusters
to get next or previous day-of-week.
private LocalDate calcNextFriday(LocalDate d) {
return d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
}