Get Day of Week From Given Date in Java

“In this tutorial, we will be solving the problem on how to get the day of the week from a given date in java.

We will be looking at where to get the above requirements.

Also, we will be going on deep on how to display the day from a given date in java.

Get Day of the week From given Date in Java

In this program, we will be using the java.time package,using import java.time.*;

The classes defined in the above package, basically represent date-time concepts including all the parameters which are date, timezones, etc.

Each class includes support for printing and parsing all manners of date as well as times.

Check these:

After importing the above package, we will be creating a class named “getday.

Inside the method, we will be creating an object of class “DayOfWeek” class.

DayOfWeek” initially stores the day-of-week on its own. This basically stores a single day onto isolation.

After the object creation, we will be now passing the date parameter inside “LocalDate.of” method.

Inside this method, we will be passing any date as required by the user along with the “getdayofweek” method.

This method gets the day of the week and is a part of the class LocalDate.

This method returns the day of the week.

After passing the parameters of date, we will be typecasting the above value we got from the object of class DayOfWeek and getting the result.

We will be converting the value to string with the method String.valueof and we have the privilege to convert any data type to string type.

This method returns the string representation of the above date.

Below is the program for getting a day of the week from a given date in java:

import java.time.*;

public class getday{
   public static void main(String[] args) {
      DayOfWeek dow = LocalDate.of(2019,Month.SEPTEMBER,28).getDayOfWeek();
      String s = String.valueOf(dow);
      System.out.println(String.format("%.3s",s));
   }
}

Lastly, we used formatting for displaying into formatted manner.

Below is sample output for the above code:

Get Day of Week From Given Date in Java

Leave a Reply

Your email address will not be published. Required fields are marked *