×

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

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.