tl;dr
LocalDate.now ( ZoneId.of ( "America/Montreal" ) )
.with ( org.threeten.extra.Temporals.previousWorkingDay () )
java.time
Java 8 and later has the java.time framework built-in. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
These new classes replace the notoriously troublesome old date-time classes bundled with the earliest versions of Java, java.util.Date/.Calendar. Avoid the old classes where possible. When you must interface look for newly added conversion methods to switch into java.time for most of your work. Also, the makers of Joda-Time have told us to move to java.time as soon as is convenient.
Basics of java.time… An Instant
is a moment on the timeline in UTC. Apply a time zone (ZoneId
) to get a ZonedDateTime
. For a date-only value without a time-of-day nor a time zone, use LocalDate
.
First we get "today" as an example date value. Note how a time zone is required in order to determine the current date even though a LocalDate
does not contain a time zone. The date is not simultaneously the same around the globe, as a new day dawns earlier in the east.
LocalDate today = LocalDate.now ( ZoneId.of ( "America/Los_Angeles" ) );
Adjustors
The ThreeTen-Extra project extends java.time with additional or experimental features. These features may or may not eventually be folded into java.time proper. This project provides a Temporals
class which provides implementations of adjustors including a couple for nextWorkingDay
and previousWorkingDay
. Easy to use as seen here.
// The 'Temporals' class is from the ThreeTen-Extra library, not built into Java.
LocalDate previousWorkingDay = today.with ( Temporals.previousWorkingDay () );
LocalDate nextWorkingDay = today.with ( Temporals.nextWorkingDay () );
When Run
Dump to console. Notice how today is a Friday, so the previous working day is -1 (yesterday, Thursday) and the next working day is +3 (Monday).
System.out.println ( "today: " + today + " | previousWorkingDay: " + previousWorkingDay + " | nextWorkingDay: " + nextWorkingDay );
today: 2016-01-22 | previousWorkingDay: 2016-01-21 | nextWorkingDay: 2016-01-25
Saturday & Sunday
This pair of adjustors simply skips over every Saturday and Sunday. It knows nothing of holidays. Nor does it know about other definitions of the working week and weekend. The class documentation suggests writing your own java.time.temporal.TemporalAdjuster is easy if you want to handle other definitions.