There are many instances when the business requirements specify implementation logic based on day of the week(Monday, Tuesday…) for a given date. Java 8 has defined a separate Enum for handling days of the week named –
This tutorial first explains the important points to keep in mind before using
DayOfWeek Enum. It then explains how to use
DayOfWeek for commonly used scenarios of getting the day of the week for a given date, and then taking a decision based on the day of the week determined with an example program.
Important points regarding
java.time.DayOfWeekis an Enum which defines
7constants representing the seven days of the week –
- It is recommended to use the
Enumconstants in code rather than their equivalent
intvalues to enhance code readability and clarity.
- Lastly, in case the use of
intvalues is required, then the value obtained for each of the constants obtained using
getValue()method should be used, and use of
ordinal()method should be avoided.
Determining the day of week, and executing conditional logic, for a given date
OUTPUT of the above code Explanation of the code
DayOfWeekExampleclass first creates an instance of
java.time.LocalDateclass, named localDate, using its
of()method. The variable holds the date
- An instance of
dayOfWeek, is obtained from
LocalDate.getDayOfWeek()method. The day of the week on
FRIDAYand the same is printed as output.
- The next section of the code shows the conditional usage of
DayOfWeekinstance by using it to determine the first working day of the year.
- The variable
dayOfWeekis passed to a
switch()statement and it has 3 cases –
- If the
2days are added to the
localDateto get the date for the nearest
2days are added using
LocalDate.plusDays()method, and assigned to the
SATURDAYthen a single day is added using
plusDays(1)and assigned to
- In all other cases, i.e.
default, it is a weekday falling between MONDAY TO THURSDAY, in which case the next working is the first working day of the year, which is obtained using
- If the
- The value determined for
firstWorkingDayis then correctly printed as
- Note – The code for using day of week remains the same if you want to use
LocalDateused above. Just change
LocalDateTimeand the rest of the code, including method name, will remain the same.
In this tutorial we understood how to get day of week for a given date using
java.time.DayOfWeek enum along with its usage for applying business logic based on the day. Given below is a list of more Java 8 Date-Time tutorials for your reference.