How to calculate the difference between two dates by ignoring weekends in Java without using a loop

Asked

Viewed 4,355 times

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;
    }
}
  • 4

    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

1 answer

3


As @Math said, the right thing would be to ask and put your answer. Then mark your answer as accepted, so the question does not appear in the unanswered OS questions.

Anyway I will add an algorithm that I use for this purpose as an answer, do not need to mark it as accepted, can respond with yours and mark it.

static long days(Date start, Date end){
    //Ignore argument check

    Calendar c1 = Calendar.getInstance();
    c1.setTime(start);
    int w1 = c1.get(Calendar.DAY_OF_WEEK);
    c1.add(Calendar.DAY_OF_WEEK, -w1);

    Calendar c2 = Calendar.getInstance();
    c2.setTime(end);
    int w2 = c2.get(Calendar.DAY_OF_WEEK);
    c2.add(Calendar.DAY_OF_WEEK, -w2);

    //end Saturday to start Saturday 
    long days = (c2.getTimeInMillis()-c1.getTimeInMillis())/(1000*60*60*24);
    long daysWithoutSunday = days-(days*2/7);

    return daysWithoutSunday-w1+w2;
}

This algorithm is based on the English OS response of this link https://stackoverflow.com/a/4600534/747802

Browser other questions tagged

You are not signed in. Login or sign up in order to post.