JodaTime: number of business days between two dates

I am looking for a way to calculate the number of working days in Joda Time. The total number of days on which I receive:

DateMidnight start = new DateMidnight(DateMidnight.now()); DateMidnight end = new DateMidnight(2014,10,10); int days = Days.daysBetween(start,end).getDays(); 

Then I would deduct the number of days off / holidays. But how do I calculate them?

I would be happy to help.

+4
source share
2 answers

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 :)

+3
source

The answer from DeezCashews worked well for me with the following additional modification ...

If you, like me, are looking for an exhaustive difference between dates and not an exceptional difference between dates (for example, a vacation request for employees from Mon 21st Nov to Fri 25th Nov should come out in 5 days, not 4), then the right approach is is to add a day to the "end" before calling the "toWorkday ()" method. Freeing up the difference at any time after this does not work due to the way the algorithm is implemented

0
source

All Articles