In this article, we will find the day of the week using the date in Java.
From Java 8, the java.time
package provides the date and time functionalities. To see the day of the week, we can use the LocalDate
class, which represents a date without a time component.
Import packages & obtain date
Let us first import the classes from thejava.time
package and obtain the date from which we find the day of the week.
You can read the date from the user or for testing purposes, you can create an LocalDate
instance by parsing a date string or using the of()
method. Following is the example:
import java.time.*;
// Parsing a date string
String dateString = "2023-07-15";
LocalDate date = LocalDate.parse(dateString);
// Using the of() method
LocalDate date = LocalDate.of(2023, 7, 15);
Find the day of the week
To find the day of the week, we can use the DayOfWeek
enum, which represents the days of the week (Monday to Sunday). The getDayOfWeek()
method on the LocalDate
instance to obtain the corresponding DayOfWeek
object and from the DayOfWeek
object, we can get the name of the day as a string.
DayOfWeek dayOfWeek = date.getDayOfWeek();
String dayName = dayOfWeek.name();
As an alternative way, we can also use the getDisplayName()
method to get the day’s name with a specific TextStyle
.
String dayName = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
Following is the output for the date “2023-07-15“:
Day of the week: SATURDAY
References:
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html