×

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section.

When dealing with Date and time in Java, the following classes are used.

  • Class for Calendars: This Class is a part of the Java.util package. It supports the Serializable, Cloneable, and ComparableCalendar> interfaces and extends the Object class. It offers ways to convert particular time instances and calendar fields (such as YEAR, MONTH, DAY, HOUR, DAY OF MONTH, etc.).
  • Class for dates: This Class is a part of the util package. With millisecond precision, it captures a particular moment in time. It converts dates into the year, month, day, hour, minute, and second values. Additionally, date strings may be formatted and parsed.
  • LocalDate Type: It is a part of the time package. It displays dates using the ISO-8601 calendar, such as 2002-08-24. It is a yyyy-mm-dd formatted date representing an immutable date-time object. Additionally, we have access to other date parameters like the year, week, and week of the year. For instance, a LocalDate can store the "22nd December 2003" value. It should be noted that the subclass does not represent or hold a time or time zone.
  • Class SimpleDateFormat: This Class is a part of the Java.text package. The DateFormat Class is extended by it. SimpleDateFormatiis a simple class for locale-sensitive date formatting and parsing.
  • Format: For formatting locale-sensitive data, such as dates, messages, and numbers, Format is an abstract base class.
  • DateFormat: The Class, DateFormat, is part of Java. text package. This Class extends the Format class.

The following methods exist for deriving day name from Date:

  • Using the SimpleDateFormat Class
  • Using the DateFormatSymbols Class
  • Using the GregorianCalendar Class
  • Using SimpleDateFormat class

The Java programme that follows shows how to obtain the day name for today's Date.

The getInstance() function of the Calendar class was called after we generated an object of the Class in the following application. A result is a Calendar object with the current time and Date initialized in each calendar field. It might generate every calendar field.

In the SimpleDateFormat class function Object () { [native code] }, a date format has been processed. The format () function of the SimpleDateFormat class, which formats the provided Date into a date/time text and concatenates the output to the specified StringBuffer, is called in the print statement. We called the getTime() function of the

Calendar class inside the format () method. The function compares a Date object that represents the time value of this Calendar.

The base class Format contains other format classes like DateFormat and SimpleDatefFormat. We supplied EEEE, which stands for the name of the day in the week, to the Format class function Object () { [native code] }. The format () method has been called, and the Date class object has been processed in the following statement. The method creates a string by formatting an object. Print the string containing the day's last name.

DayName1.java

import java.text.Format;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.Calendar;  
public class DayName1
{  
public static void main (String args[]) throws Exception   
{  
// produces a Calendar object with its calendar fields initialized with the time and Date of the moment.
Calendar cobj = Calendar.getInstance();  
// Object creation for the SimpleDateFormat class  
SimpleDateFormat object = new SimpleDateFormat("dd-MM-yyyy");  
// Loading the current date using getTime()  
System.out.println("Current date: " + object.format(cobj.getTime()));  
// Object creation for the Format class  
// Full day name forming from format () method  
Format form = new SimpleDateFormat("EEEE");  
String day = form.format(new Date());  
// Printing day name of current Date
System.out.println("Current Day Name: " + day);  
}  
}  

Output:

Current Date: 20-09-2022
Current Day Name: Tuesday 

We can specify the date format as you wish; let’s see a program for that,

import java.text.Format;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.Calendar;  
public class JavaCallable
{  
public static void main (String args[]) throws Exception   
{  
// produces a Calendar object with its calendar fields initialized with the time and Date of the moment.
Calendar cobj = Calendar.getInstance();  
// Object creation for the SimpleDateFormat class  
SimpleDateFormat object = new SimpleDateFormat("yyyy-MM-dd");  
// Loading the current date using getTime()  
System.out.println("Current date in specified pattren: " + object.format(cobj.getTime()));  
// Object creation for the Format class  
// Full day name forming from format () method  
Format form = new SimpleDateFormat("EEEE");  
String day = form.format(new Date());  
// Printing day name of current Date
System.out.println("Current Day Name: " + day);  
}  
}  

Output

Current Date in specified pattren: 2022-08-21
Current Day Name: Tuesday

Now let’s see another program using DateFormatSymbol class

Using DateFormatSymbols class

The getWeekdays () method, which returns a string of weekdays, has been called in the following program's function Object () { [native code] } of the DateFormatSymbols() class. Weekdays are kept in an array called dayNames [].

The getInstance () function of the Calendar class was then called after we had generated an instance of it. A result is a Calendar object with the current Date and time initialized in each calendar field. It might create every calendar field.

We called the get () function of the Calendar class in the print statement and gave the field DAY OF WEEK as an argument. It obtains the get and set numbers, which indicate what day it is.

As a result, the day of the week is printed.

DayName2.java

import java.util.Calendar;  
import java.text.SimpleDateFormat;  
import java.text.DateFormat;  
import java.text.DateFormatSymbols;  
public class DayName2 
{  
public static void main(String args[])   
{  
// String array for storing the weekdays using the getweekdays() method
String Days[] = new DateFormatSymbols().getWeekdays();  
// Object creation for calender class
Calendar Curdate = Calendar.getInstance();  
// Printing the current day from a string array of days
System.out.println("Current day is "+ Days [Curdate.get(Calendar.DAY_OF_WEEK)]);  
}  
}  

Output:

Current day is Tuesday

Now let’s see another program using GregorianCalendar class.

Using GregorianCalendar class

The Java.util package contains classes for Gregorian calendars. It belongs to the Calendar class's concreate subclass. It offers the conventional calendar structure.

The GregorianCalendar class object was parsed as an argument, and a new instance of the Date class was produced in the example below. We entered the year, the month, and the day of the month for which we wanted to know the day in the function Object () { [native code] } of the GregorianCalendar Class.

The Date object's representation of the number of milliseconds from January 1, 1970, 00:00:00 GMT, is returned by the getTime() method. The function Object () constructor of the Date class generates a Date object and initializes it to reflect the time, accurate to the closest millisecond at which it was allotted.

The day name of a given date can be found using the method dayName() that we developed. We have constructed a function Object () constructor for the SimpleDateFormat class inside the method and parsed the pattern for the day name, which is EEEE.

DayName3.java

import java.util.*;  
import java.text.SimpleDateFormat;  
import java.text.DateFormat;  
public class DayName3
{  
public static void main (String args[])   
{  
Date Date1 = (new GregorianCalendar (2003, Calendar.JUNE, 1)).getTime();  
// Object creation for Date class 
Date Date2 = new Date ();  
// Priting the day name using the method dayName()  
System.out.println("The day on the date was: " + dayName(Date1));  
}  
// method that detemines the day name from the given Date
public static String dayName(Date d)   
{  
// Creating the format for representing the day  
DateFormat format = new SimpleDateFormat("EEEE");  
try   
{  
return format.format(d);  
}  
catch (Exception ae)   
{  
ae.printStackTrace();  
return "";  
}  
}  
}  

Output:

The day on the Date was: Sunday

Now let’s see another program for finding the day name.

DayName4.java

import java.time.LocalDate;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
public class JavaCallable 
{  
public static void main(String args[])      
{  
try  
{  
// Object creation for SimpleDateFormat class
SimpleDateFormat Datef = new SimpleDateFormat("dd/MM/yyyy", java.util.Locale.ENGLISH); 
// Parsing the date format 
Date D = Datef.parse("01/06/2022");  
// The pattern in which the Date is represented 
Datef.applyPattern("EEE, d MMM yyyy");  
// storing the day in the string 
String days = Datef.format(D);  
// Printing the given dates day   
System.out.println(days);  
}  
catch (Exception ae)  
{  
ae.printStackTrace();  
}  
}  
} 

Output:

Wed, 1 Jun 2022

Conclusion

This is how you can get the day name from the specified or current Date. You can use any method that is mentioned above for getting the day name from the Date. You can select any of the class types mentioned above for this purpose. You may choose the Class even based on the situation, like the current day or the day of the specified Date, so you may select the Class for getting the day name as per the situation.


Related Topics

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.