8
I was looking for a solution to this problem but I did not find a satisfactory algorithm, so I decided to create the algorithm. I hope it fits someone.
public int betweenDaysIgnoreWeekends(DateTime startDate, DateTime endDate) {
//Um numero que representa o dia da semana para a data final, exemplo segunda=1, terça=2, quarta=3...
int dayOfWeekEndDateNumber = Integer.valueOf(endDate.dayOfWeek()
.getAsString());
//Um numero que representa o dia da semana para a data inicial, exemplo segunda=1, terça=2, quarta=3...
int dayOfWeekStartDateNumber = Integer.valueOf(startDate.dayOfWeek()
.getAsString());
//Se a data final for sabado ou domingo, finja ser sexta-feira
if (dayOfWeekEndDateNumber == 6 || dayOfWeekEndDateNumber == 7) {
int DaysToAdd = 8 - dayOfWeekEndDateNumber;
endDate = endDate.plusDays(DaysToAdd);
dayOfWeekEndDateNumber = Integer.valueOf(endDate.dayOfWeek()
.getAsString());
}
//Se a data inicial for sabado ou domingo, finja ser segunda-feira
if (dayOfWeekStartDateNumber == 6 || dayOfWeekStartDateNumber == 7) {
int DaysToAdd = 8 - dayOfWeekStartDateNumber;
startDate = startDate.plusDays(DaysToAdd);
dayOfWeekStartDateNumber = Integer.valueOf(startDate.dayOfWeek()
.getAsString());
}
//Quantos dias se passaram contando os fins de semana
int days = Days.daysBetween(startDate, endDate).getDays();
//Quantas semanas se passaram exatamente
int weeks = days / 7;
//O excesso de dias que sobrou, exemplo: 1 semana e 3 dias o excess=3 e weeks=1
int excess = days % 7;
//Se a data inicial for igual a data final, passou 0 dia
if (startDate.equals(endDate)) {
return 0;
} else {
//O excesso de dias passou pelo fim de semana, então deve-se retirar 2 dias
//da quantidade final de dias
if (excess + dayOfWeekStartDateNumber >= 6) {
//Quantidade de semanas * 5 dias uteis + o excesso de dias - o final de semana que o excesso atravessou
return weeks * 5 + excess - 2;
}
//Quantidade de semanas * 5 dias uteis + o excesso de dias
return weeks * 5 + excess;
}
}
Cool your algorithm, but there’s a little problem with how you’re conveying your knowledge, you should ask a question and answer it yourself, as if it were two different people, one asking and the other answering. Take a look at this link here
– Math