Calculating due date counting only working days

PDF

Recently I was required to calculate an expected due date based on office working. Shockingly, this is not readily available in the SDK or even as a well-known Open Source library.

Jollyday to the rescue! And some fancy Java Streams.


Introducing Jollyday

Jollyday is a small and a little bit outdated library, that still does a fine job if you use it straightforwardly.

It has all kinds of rules with which you can have a dynamically calculated holiday in case it moves if it is in the weekend (like Holland’s King’s Day, which moves to Saturday if it is on a Sunday). It also has validity directives so you can specify different rules for different years of the same holiday, such as when our Queen’s Day moved when we got a new Queen.

It even includes Easter, which requires insane math!

Let’s calculate the due date!

Configure the weekends

We’ll use JDK date time API for defining the Weekend.

with the above, you can now do something like WEEKEND_DAYS.contains(myLocalDate.getDayOfWeek()).

There are other ways to determine if a given date lies in the Weekend, but it’s not as readable:

localDate.getDayOfWeek().getValue() >= DayOfWeek.SATURDAY.getValue())

Or using a TemporalQuery:

localDate.query(t -> t.get(ChronoField.DAY_OF_WEEK) >= 5).

Configure the holidays

Either pick a country ready to go or, if you want to configure it further, take one of the country XML’s from the library and create your own. We’ll do just that and create a new Holidays config named creatively: “MyList”.

Now to get these holidays in Java:

Determine due date

With the weekends and holidays set, we can use Java streams to find the due date rather elegantly:

Here’s what happens:

  • Generate an infinite list starting with a date and adding one day each iteration.
  • Filter out any holiday or weekend days
  • Keep the other days until the stream limit was reached, indicated by the number of working days we want to count
  • Using Guava’s Iterables.getLast we return the date found after counting operational working days.

Leave a Reply