The secret is to use u
in the default SimpleDateFormat
, as in the code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class ProximoDiaDaSemana {
private static DateFormat DIA_DA_SEMANA = new SimpleDateFormat("u");
private static long MILISEGUNDOS_EM_UM_DIA = 24 * 60 * 60 * 1000;
private static int DOMINGO = 7;
private static int SABADO = 6;
private static int diferencaSabadoOuDomingo(int diaDaSemana) {
if (diaDaSemana == DOMINGO) {
return 1;
}
if (diaDaSemana == SABADO) {
return 2;
}
return 0;
}
private static Date obterDataProximoCompromisso(Date dataInicial, int dias) {
Date daquiXDias = new Date(dataInicial.getTime() + dias * MILISEGUNDOS_EM_UM_DIA);
int diferencaSabadoOuDomingo = diferencaSabadoOuDomingo(Integer.valueOf(DIA_DA_SEMANA.format(daquiXDias)));
if (diferencaSabadoOuDomingo > 0) {
return new Date(daquiXDias.getTime() + diferencaSabadoOuDomingo * MILISEGUNDOS_EM_UM_DIA);
} else {
return daquiXDias;
}
}
}
So when we run a test:
private static DateFormat EXIBICAO = DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());
public static void main(String[] args) {
Locale.setDefault(new Locale("pt-BR"));
Date hoje = new Date();
System.out.println("Hoje: " + EXIBICAO.format(hoje));
for (int i = 1; i <= 15; i++) {
System.out.println("Se agendar para daqui " + i + " dias cairá em: "
+ EXIBICAO.format(ProximoDiaDaSemana.obterDataProximoCompromisso(new Date(), i)));
}
}
We have the desired result:
Today: Friday, July 10, 2015
If scheduled for 1 day will fall on: Monday, July 13,
2015
If scheduled for 2 days, it will fall on: Monday, July 13,
2015
If scheduled for 3 days will fall on: Monday, July 13,
2015
If scheduled for 4 days will fall on: Tuesday, July 14,
2015
If scheduled for 5 days will fall on: Wednesday, July 15,
2015
If scheduled for 6 days will fall on: Thursday, July 16,
2015
If scheduled for 7 days will fall on: Friday, July 17,
2015
If scheduled for 8 days will fall on: Monday, July 20,
2015
If scheduled for 9 days will fall on: Monday, July 20,
2015
If scheduled for 10 days will fall on: Monday, July 20,
2015
If you schedule for here 11 days will fall on: Tuesday, July 21,
2015
If scheduled for 12 days from now, it will fall on: Wednesday, July 22,
2015
If scheduled for 13 days will fall on: Thursday, July 23,
2015
If scheduled for 14 days, it will fall on: Friday, July 24,
2015
If scheduled for 15 days, it will fall on: Monday, July 27,
2015