Java Localdate Getdayofweek Method

JavaJavaBeginner
Practice Now

Introduction

The getDayOfWeek() method is used to retrieve the day of the week of a given date. It is a part of the java.time.LocalDate class in Java. This method returns an object of the java.time.DayOfWeek enum that represents the day of the week for the given date.

Create a new Java file

Navigate to the project directory and create a new Java file named GetDayOfWeekDemo.java.

cd ~/project
touch GetDayOfWeekDemo.java

Import required packages and create a main method

Now, open the GetDayOfWeekDemo.java file in your text editor and import the following packages:

import java.time.DayOfWeek;
import java.time.LocalDate;

After importing the packages, create a main method inside the GetDayOfWeekDemo class.

public class GetDayOfWeekDemo {
  public static void main(String[] args) {

  }
}

Define a LocalDate object

Inside the main method, create a LocalDate object with a specified date using the of() method.

LocalDate localDate = LocalDate.of(2021, 8, 25);

Get the day of the week using getDayOfWeek()

Now that we have a LocalDate object, we can use the getDayOfWeek() method to retrieve the day of the week for the specified date.

DayOfWeek dayOfWeek = localDate.getDayOfWeek();

Print the day of the week

We can now print the day of the week using the toString() method on the DayOfWeek object.

System.out.println("Day of the week: " + dayOfWeek.toString());

Compile and run the program

Save the changes to the file and compile the GetDayOfWeekDemo.java file using the javac command.

javac GetDayOfWeekDemo.java

After successful compilation, execute the program using the java command.

java GetDayOfWeekDemo

This will output the day of the week for the specified date.

Try with different date

Modify the date in the LocalDate object to get the day of the week for a different date.

LocalDate localDate = LocalDate.of(2021, 8, 30);

Try with current date

To get the day of the week for the current date, we can simply create a LocalDate object with no arguments.

LocalDate localDate = LocalDate.now();

Try with more complex example

To get the day of the week for a date far in the future, let's say in the year 2050, simply change the values passed to the of() method.

LocalDate localDate = LocalDate.of(2050, 12, 25);

Summary

In this lab, we learned how to use the Java getDayOfWeek() method to retrieve the day of the week for a given date. Follow the above step-by-step guide to run the code successfully in the terminal of the Ubuntu system.

Other Java Tutorials you may like