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
, who already owns a adjuster ready to return the next Monday:
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 little 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 this 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 fall in weekend, adjusts for the next Monday), but as Temporal
does not have the methods plusDays
and getDayOfWeek
, the implementation is a little 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 method with
:
LocalDate dataEnvio = ...
LocalDate doisDiasDepois = dataEnvio.with(somarDiasUteis(2));
The advantage is that this adjuster serves for any type that implements Temporal
(i.e., all native types of the API, such as LocalDateTime
, ZonedDateTime
, etc), provided they have the date fields, of course (LocalTime
, for example, there is no day, so it would not work with this class).
Define working days.
– Maniero
Monday to Friday.
– user63513