Learn to find the day of the week for a given date using the legacy Date and Calendar classes as well as the new Java 8 Date API.
1. Overview
There may be a requirement to show the day of the week (Monday to Sunday) in the UI, and then we need to find this information.
- With Java 8 Date API, we have a dedicated enum DayOfWeek starting from
Monday (1)
toSUNDAY (7)
. We can use theLocalDate.getDayOfWeek()
method to the day value. - In Java, legacy Calendar class defines the 7 constants from
SUNDAY (1)
toSATURDAY(7
). We can a day from Calendar instance using thecal.get(Calendar.DAY_OF_WEEK)
method.
It is crucial to notice the difference in the numbers assigned to weekdays in both solutions.
2. Get the Day of Week using LocalDate (Java 8)
Let us see a program to demonstrate how to get the day of the week using LocalDate class and DayOfWeek enum since Java 8.
LocalDate today = LocalDate.now();
DayOfWeek dayOfWeek = today.getDayOfWeek();
System.out.println("Day of the Week :: " + dayOfWeek);
System.out.println("Day of the Week - in Number :: "
+ dayOfWeek.getValue());
System.out.println("Day of the Week - Formatted FULL :: "
+ dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()));
System.out.println("Day of the Week - Formatted SHORT :: "
+ dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.getDefault()));
Program output.
Day of the Week :: TUESDAY
Day of the Week - in Number :: 2
Day of the Week - Formatted FULL :: Tuesday
Day of the Week - Formatted SHORT :: Tue
3. Get the Day of Week using Calendar (Java 7)
Now let us find the day of the week using the legacy Java classes java.util.Date and Calendar.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int dayOfWeekNum = cal.get(Calendar.DAY_OF_WEEK);
DateFormat formatter = new SimpleDateFormat("EEEE");
String dayOfWeekString = formatter.format(cal.getTime());
System.out.println("Day of the Week - in Number :: " + dayOfWeekNum);
System.out.println("Day of the Week - in Text :: " + dayOfWeekString);
Program output.
Day of the Week - in Number :: 3
Day of the Week - in Text :: Tuesday
4. Conclusion
Clearly, old Java classes had minimal support for getting the name of weekdays. Since Java 8, new date-time APIs have solid support and even a dedicated enum for this purpose.
Happy Learning !!