One option is to add 2 days, and if the result falls on a Saturday or Sunday, set the date for next Monday.
You can use the class java.time.temporal.TemporalAdjusters
, which already has an adjuster ready to return to the next second:
LocalDate dataEnvio = ...
// somar dois dias
LocalDate doisDiasDepois = dataEnvio.plusDays(2);
// se caiu em um fim de semana (sábado ou domingo)
if (doisDiasDepois.getDayOfWeek() == DayOfWeek.SATURDAY
|| doisDiasDepois.getDayOfWeek() == DayOfWeek.SUNDAY) {
// ajustar para a próxima segunda-feira
doisDiasDepois = doisDiasDepois.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
}
if (doisDiasDepois.isBefore(LocalDate.now())) {
...
}
If you want, you can use import static
to make the code a bit more readable:
import static java.time.temporal.TemporalAdjusters.next;
import static java.time.DayOfWeek.*;
// ....
// se caiu em um fim de semana
if (doisDiasDepois.getDayOfWeek() == SATURDAY
|| doisDiasDepois.getDayOfWeek() == SUNDAY) {
// ajustar para a próxima segunda-feira
doisDiasDepois = doisDiasDepois.with(next(MONDAY));
}
Another alternative is to implement your own TemporalAdjuster
. The difference is that it works with the interface java.time.temporal.Temporal
(instead of working with a specific type, such as LocalDate
).
The logic is the same (add 2 days, if it falls on the weekend, it adjusts for the next second), but since Temporal
does not have the plusDays
and getDayOfWeek
methods, the implementation is slightly different :
public TemporalAdjuster somarDiasUteis(long dias) {
return temporal -> {
// somar a quantidade de dias
temporal = temporal.plus(dias, ChronoUnit.DAYS);
DayOfWeek dow = DayOfWeek.from(temporal);
// se cai em fim de semana, ajusta para a próxima segunda
if (dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY) {
temporal = temporal.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
}
return temporal;
};
}
To use, just pass the result to the with
method:
LocalDate dataEnvio = ...
LocalDate doisDiasDepois = dataEnvio.with(somarDiasUteis(2));
The advantage is that this adjuster is for any type that implements Temporal
(that is, all native API types such as LocalDateTime
, ZonedDateTime
, they have the date fields, of course ( LocalTime
, for example, there is no day, so it would not work with this class).