This article contains examples of getting weekdays from java date.
We used the Java 8 time module and its LocalDate class, then we used the getDayOfWeek() method of this class to fetch the day name.
public DayOfWeek getDayOfWeek()
// It returns DayOfWeek enum value
We will see the examples based on these scenarios:
Let's get started with some running examples.
Here, we used the static now() method of LocalDate class to get the current local-date. After that, we used the getDayOfWeek() method that returns the name of the week.
The returned value is actually a value of DayOfWeek enum.
import java.time.DayOfWeek;
import java.time.LocalDate;
/*
* Code example to Get Day of Week from local date in Java
*/
public class JExercise {
public static void main(String[] args) {
// Current Date
LocalDate localDate = LocalDate.now();
System.out.println("Date: "+localDate);
// Get Day of Week
DayOfWeek week = localDate.getDayOfWeek(); // returns an enum value
System.out.println("Day of Week: "+week);
}
}
Output:
Date: 2021-02-24
Day of Week: WEDNESDAY
If you already have any string date then first convert it into the LocalDate instance using the parse() method.
After getting the local date, call the getDayOfWeek() method that returns the week name.
import java.time.DayOfWeek;
import java.time.LocalDate;
/*
* Code example to Get Day of Week from local date in Java
*/
public class JExercise {
public static void main(String[] args) {
// Some Date
String date = "2015-12-10";
LocalDate localDate = LocalDate.parse(date);
System.out.println("Date: "+localDate);
// Get Day of Week
DayOfWeek week = localDate.getDayOfWeek();
System.out.println("Day of Week: "+week);
}
}
Output:
Date: 2015-12-10
Day of Week: THURSDAY