I had to understand this today and did not like any of the answers that I saw on the Internet. So here is my solution for everyone who comes across this. Please note that I assume that if the beginning or the end is at the weekend, I do it the next business day (Sat or Sun becomes the next Monday). After that, it is as simple as getting the number of days between them, and then finding out the number of days off between them and finally subtracting 2 days for each weekend:
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 that someone will come and comment that not everyone has the same weekend as blah blah blah. I leave language differences as an exercise for those who do this :)
source share