To get the day of the week from a date-time in Java, we can use the getDayOfWeek() method of LocalDateTime class.
This method returns day names such as Monday, Tuesday, etc from the date-time object.
For example, if you want to know the name of the day on "2022-02-14T17:28:13.048999208", then the result will be "MONDAY".
Let's understand with the running examples.
Here, we are getting name of the weekday from a date-time by using the getDayOfWeek() method. First, we created a date-time object from string date by using the parse() method. See the Java code below.
/*
* Code example to get day of week from localdatetime in Java
*/
import java.time.LocalDateTime;
import java.time.DayOfWeek;
public class JExercise {
public static void main(String[] args) {
// String date is given
String strDate = "2022-02-14T17:28:13.048999208";
// parse the date into date time
LocalDateTime date = LocalDateTime.parse(strDate);
// Displaying date and time
System.out.println("Date : "+date);
// Get day of week from the date
DayOfWeek month = date.getDayOfWeek();
// Display result
System.out.println("Weekday Name : "+month);
}
}
Output:
Date : 2022-02-14T17:28:13.048999208
Weekday Name: MONDAY
Now, let's see its signature
public DayOfWeek getDayOfWeek()
Package Name: java.time;
Class Name: LocalDateTime
Return Value: It returns the day-of-week field, which is an enum DayOfWeek, not null.
Parameters: No
Version: Since 1.8
Let's see some more examples.
We can also get the day name of the week from the current date-time. Here, we first used the now() method to get the current local date-time and then used the getDayOfWeek() method. See the below Java code.
/*
* Code example to get day of week from localdatetime in Java
*/
import java.time.LocalDateTime;
import java.time.DayOfWeek;
public class JExercise {
public static void main(String[] args) {
// Current date and time
LocalDateTime date = LocalDateTime.now();
// Displaying date and time
System.out.println("Date : "+date);
// Get day of week from the date
DayOfWeek month = date.getDayOfWeek();
// Display result
System.out.println("Weekday Name : "+month);
}
}
Output:
Date : 2022-03-15T19:14:46.784514294
Weekday Name: TUESDAY
Use this code to get results in a single line of code. If you are a beginner, skip this code.
LocalDateTime.now().getDayOfWeek();
This code will return the day of the week from the current date. You just need to copy this code and get the result instantly.