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.