×

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application.

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

  • Class for Calendars: This class is a part of the Java.util package. It satisfies the Serializable, Cloneable, and Comparable<Calendar> interfaces and extends the Object class. It offers ways to convert particular instances of time as well as a number of calendar fields (such 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 enables the conversion of dates into values for the year, month, day, hour, minute, & second. Additionally, date strings may be formatted and parsed.
  • LocalDate Class: A time package class. It displays dates using the ISO-8601 calendar, such as 2002-05-17. It is a yyyy-mm-dd formatted date that is represented as 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 value "12th Feburary 2005". It should be noted that the class doesn't really represent or hold a time or time zone.
  • Class SimpleDateFormat: The java.text package contains the class. The DateFormat class is extended by it. SimpleDateFormat is an abstract class for locale-sensitive date formatting and parsing.
  • For formatting locale-sensitive data, such as dates, messages, & numbers, Formatting is an abstract base class.
  • The class, DateFormat, is part of the Java.text package. This class extends Format.

The following methods exist for deriving day name from date:

  • Employing the SimpleDateFormat Class
  • DateFormatSymbols Class Utilization
  • GregorianCalendar Class Utilization

There are several classes that can be utilized to represent Date in the new java.time package.

The additional data that each class stores in additional to the Date makes a difference.

While LocalDateTime has both date and time information, the basic LocalDate only contains the date information.

Similar to this, more complex classes like OffsetDateTime and ZonedDateTime each contain more details about the offset from UTC and the time zone, respectively.

Anyhow, all of these classes include direct methods for extracting the Year, Month, and Date data.

Let's look at these techniques for getting data from a LocalDate object called localDate.

LocalDate just offers a getYear() function to extract Year:

localDate.getYear () ;

Similarly, we employ the getMonthValue API to extract Month:

localDate.getMonthValue () ;

Finally, we have the getDayOfMonth function to retrieve Day:

localDate.getDayofMonth () ;

By using java.util.Date

In order to extract specific fields from a given java.util.Date, like Year, Month, Day, etc., we must first convert the date to a Calendar instance.

Date date; / / the date instance
Calendar calendar = Calendar.getInstance () ;
Calendar.setTime(date) ;

When we possess a Calendar instance, then can call its get method directly and pass it the particular field we wish to retrieve.

Constants found in the Calendar can be used to extract particular fields.

To Get Year:

By providing Calendar.YEAR as just an argument to get, we can get the year:

calendar.get(Calendar.YEAR);

To Get Month:

Similarly, we may call get through providing Calendar.MONTH as just an argument to extract the month:

calendar.get(Calendar.MONTH) ;

To Get Day:

Finally, we call get and pass the argument Calendar.DAY OF MONTH to extract the day:

calendar.get(Calendar.DAY_OF_MONTH);

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

The getInstance() function of a Calendar class was called after we generated an instance of it in the following application. The result is a Calendar object that has the current time and date initialized in each of its calendar fields. It might generate every calendar field.

With in SimpleDateFormat class constructor, a date format has been processed. The format() function of the SimpleDateFormat class, which formats a given Date into a date/time string & appends the output to the specified StringBuffer, is called in the print statement. We had used to getTime() method of a Calendar class inside the format() method. The function compares a Date object that represents the time value of this Calendar.

The base class Shape and form 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 constructor. 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 name last.

A Sample program on getting the day from the date in java:

GetDayName.java

import java.text.Format;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.Calendar;  
public class GetDayName 
{  
public static void main(String args[]) throws Exception   
{  
//returns a Calendar objects with calendar fields set to the current date and time.
Calendar cal = Calendar.getInstance();  
//giving the SimpleDateFormat class a constructor
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");  
//getting the current date  
System.out.println("Today's date: "+sdf.format(cal.getTime()));  
//the Format class's constructor being created 
//displaying the full-day name  
Format f = new SimpleDateFormat("EEEE");  
String str = f.format(new Date());  
//prints the day name  
System.out.println("Day Name: "+str);  
}  
}  

Output :

Today's date: 21-11-2022Day Name: Monday

Using The DateFormatSymbols Class :

We have created a constructor for the DateFormatSymbols in the program below ()

then used the getWeekdays() method, which returns a string containing the weekdays. Weekdays are kept in an array called day Names[].

The getInstance() function of a Calendar class was then called after we had generated an instance of it. The result is a Calendar object that has the time and date initialized in each of its calendar fields. It might generate every calendar field.

We called just get() method of a Calendar class in the information provided and gave the field DAY OF WEEK as an arguments. It obtains the get and set numbers, which indicate the day of the week.

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

A Sample Program on GetDayExample.Java:

import java.util.Calendar;  
import java.text.SimpleDateFormat;  
import java.text.DateFormat;  
import java.text.DateFormatSymbols;  
public class GetDayNameExample 
{  
public static void main(String args[])   
{  
String dayNames[] = new DateFormatSymbols().getWeekdays();  
Calendar date = Calendar.getInstance();  
System.out.println("Today is "+ dayNames[date.get(Calendar.DAY_OF_WEEK)]);  
}  
}  

Output:

Today is Tuesday

GregorianCalendar Class Utilization

Java The Java.util package contains the GregorianCalendar Class. It belongs to the Calendar class's      

concreate subclass. It offers the conventional calendar structure.

The Date object's representation of a number of milliseconds after January 1, 1970, 00:00:00 GMT, is

returned by the getTime() method. The constructor of the Date class creates a Date object and

resets 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 had also created a constructor for the SimpleDateFormat class inside the method and parsed the pattern for the day name, which is EEEE.

import java.util.*;  
import java.text.SimpleDateFormat;  
import java.text.DateFormat;  
public class GetDayNameExample3  
{  
public static void main(String args[])   
{  
Date d1 = (new GregorianCalendar (2003, Calendar.MARCH , 21)).getTime();  
//creating a Date class constructor 
Date d2 = new Date();  
//the procedure is called, and the day's name is printed  
System.out.println("This date was on: " + dayName(d1));  
}  
//how to find the name of the day 
public static String dayName(Date d)   
{  
//EEEE stands for the whole day name.  
DateFormat f = new SimpleDateFormat("EEEE");  
try   
{  
return f.format(d);  
}  
catch(Exception e)   
{  
e.printStackTrace();  
return "";  
}  
}  
}  

Output  :

This date was on: Friday

Let's take a look at another similar Java program.

GetDayNameExample4.java

import java.time.LocalDate;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
public class GetDayNameExample4  
{  
public static void main(String args[])      
{  
try  
{  
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", java.util.Locale.ENGLISH);  
Date date= sdf.parse("21/03/2011");  
//defines the print pattern  
sdf.applyPattern("EEE, d MMM yyyy");  
String str = sdf.format(date);  
//day name and date are printed. 
System.out.println(str);  
}  
catch (Exception e)  
{  
e.printStackTrace();  
}  
}  
}  

Output  :

Mon, 21 Mar 2011

What does Java's calendar getInstance() function do?

To obtain a calendar with the system's current time zone & locale, use the getInstance() function of the Calendar class. The technique doesn't require any parameters. The method's return value is the calendar.

What does Java's getName () do?

In the File class, the getName() method has been included. The Name of a requested file object is returned by this function. The returned object by the function is a string that contains the Name of a supplied file object. A null string is provided if there is no name in the abstract path.


Related Topics

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 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.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.