In the previous section, we explored the Date class, where we learned about Date methods and how to operate on them using simple date format standards. In this section, we will learn about the Calendar class, which is similar to the Date class, but with some extra features. Let's see what they are and how we can use them to extract our date formats using the Calendar class.
First, we will create a class with a different name to avoid conflict. To create a Calendar instance, run the following:
Calendar cal=Calendar.getInstance();
Date d=new Date();
The steps are similar to those for the Date class. However, the Calendar object has some unique features that date doesn't support. Let's explore them.
Use the following code snippet:
Calendar cal=Calendar.getInstance();
SimpleDateFormat sd=new SimpleDateFormat("M/d/yyyy hh:mm:ss");
System.out.println(sd.format(cal.getTime()));
The output for the preceding code will be:
Now, suppose we want to print the day of the month and week too. We will add the following line of code to the preceding snippet:
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.DAY_OF_WEEK_IN_MONTH));
The output will be as follows:
Similarly, we can see from the following screenshot that there are multiple properties to choose from:
Thus, here we have used the Calendar instance to actually get the system date and time, but in the previous class we used Date instance; that's the only difference. A lot of methods are present in this Calendar instance that you will not find in the Date class.
This is how the system date can be retrieved as per our requirements.