Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JodaTime: Number of Businessdays between two dates

Tags:

java

jodatime

I´m searching for a way to calculate the number of business days in Joda Time. The overall number of days i get with:

DateMidnight start = new DateMidnight(DateMidnight.now());
DateMidnight end =  new DateMidnight(2014,10,10);

int days = Days.daysBetween(start,end).getDays();

Then i would subtract the number of weekend-/holidaydays. But how do i calculate them?

Would be glad about help.

like image 686
user2032869 Avatar asked Feb 01 '13 14:02

user2032869


1 Answers

Had to figure this out today and didn't like any of the answers I saw online. So here's my solution for anyone else who comes across this. Note that I assume that if start or end is on a weekend, I make it the next business day (Sat or Sun becomes the following Monday). After that its as simple as getting the number of days between, then figuring out the number of weekends between, and finally subtracting 2 days for every weekend there is:

public class DateUtil {

  public static final int DAYS_PER_WEEKEND = 2;
  public static final int WEEK_START = DateTimeConstants.MONDAY;
  public static final int WEEK_END = DateTimeConstants.FRIDAY;

  public static int workdayDiff(Date d1, Date d2) {
    LocalDate start = LocalDate.fromDateFields(d1);
    LocalDate end = LocalDate.fromDateFields(d2);

    start = toWorkday(start);
    end = toWorkday(end);

    int daysBetween = Days.daysBetween(start, end).getDays();
    int weekendsBetween = Weeks.weeksBetween(start.withDayOfWeek(WEEK_START), end.withDayOfWeek(WEEK_START)).getWeeks();

    return daysBetween - (weekendsBetween * DAYS_PER_WEEKEND);
  } 

  public static LocalDate toWorkday(LocalDate d) {
    if (d.getDayOfWeek() > WEEK_END) {
      return d.plusDays(DateTimeConstants.DAYS_PER_WEEK - d.getDayOfWeek() + 1);
    }
    return d;
  }
}

I'm sure someone will come along and comment that not everyone has the same weekends blah blah blah. I leave locale differences as an exercise for those who do :)

like image 71
DeezCashews Avatar answered Nov 14 '22 23:11

DeezCashews