×

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 Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.